我有一个类似的问题,并试图用代码来描述它,因为它更容易解释。
基本上我有一个通用集合,所以不管它被实例化为哪种类型的集合,它都会有一些共同的属性和事件。我对这些常见的属性很感兴趣。
说,我有通用集合的实例化对象 - 获取这些属性并订阅事件的最佳方法是什么?我知道我可以通过实现一个接口并将其转换为接口定义来做到这一点,但我不喜欢这样做,因为我这样做只是为了满足一个要求。有没有更好的方法来重构它?
public interface IDoNotLikeThisInterfaceDefinitionJustToPleaseGetDetailMethod
{
string Detail { get; }
event Action<bool> MyEvent;
}
public class MyList<T> : List<T>
//, IDoNotLikeThisInterfaceDefinitionJustToPleaseGetDetailMethod
{
public string Detail
{
get;
}
}
class Program
{
static void Main(string[] args)
{
MyList<int> mi = new MyList<int>();
MyList<string> ms = new MyList<string>();
MyList<char> mc = new MyList<char>();
GetDetail(mi);
GetDetail(ms);
GetDetail(mc);
}
//please note that obect need not be mylist<t>
static string DoSomeWork(Object object)
{
//Problem: I know myListObect is generic mylist
//but i dont know which type of collection it is
//and in fact i do not care
//all i want is get the detail information
//what is the best way to solve it
//i know one way to solve is implement an interface and case it to get details
var foo = myListObject as IDoNotLikeThisInterfaceDefinitionJustToPleaseGetDetailMethod;
if (foo != null)
{
//is there another way?
//here i also need to subsribe to the event as well?
return foo.Detail;
}
return null;
}
}