我有一个类似的问题,并尝试用代码来描述它,因为它更容易解释。
基本上我有一个通用集合,因此无论其实例化为哪种类型的集合,它都会有一些共同的属性和事件。我对这些共同的属性很感兴趣。
比如说,我有通用集合的实例化对象 - 获取这些属性并订阅事件的最佳方法是什么?我知道我可以通过实现一个接口(interface)并将其转换为接口(interface)定义来做到这一点,但我不喜欢这样做,因为我这样做只是为了满足单个需求。有没有更好的方法来重构这个?
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;
}
}
最佳答案
您可以使您的方法通用:
static string GetDetail<T>(MyList<T> myList)
{
return myList.Detail;
}
这将允许您使用已编写的相同代码来调用它,并完全消除该接口(interface)。
<小时/>编辑回应评论:
鉴于您不知道类型,并且您只是检查对象
,看来接口(interface)确实是最好的方法。提供通用接口(interface)允许您公开所需的所有成员,无论集合中包含什么内容,这都提供了正确的行为。
关于c# - 自定义通用集合 - 重构它的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17175227/