c# - 自定义通用集合 - 重构它的最佳方法是什么?

标签 c# .net

我有一个类似的问题,并尝试用代码来描述它,因为它更容易解释。

基本上我有一个通用集合,因此无论其实例化为哪种类型的集合,它都会有一些共同的属性和事件。我对这些共同的属性很感兴趣。

比如说,我有通用集合的实例化对象 - 获取这些属性并订阅事件的最佳方法是什么?我知道我可以通过实现一个接口(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/

相关文章:

C# Access Db 更新查询不起作用

c# - .Net Regex 用捕获组替换模式的重复出现

c# - 回绕速率限制 API 调用

c# - 为什么 Xml 文档的 selectSingleNode 有空值?

mysql - 在一条语句中使用多个 SQL 查询

C#上传视频到Youtube,不提示用户登录: Youtube API V3

c# - TransactionScope 内的父子插入导致外键约束错误

c# - 从 shell 运行的 ffmpeg 运行正常,但在 .NET 中调用时运行不正常

具有 linq 搜索条件的 C# 泛型

c# - .NET 中属性的性能开销