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

时间:2013-06-18 17:29:46

标签: c# .net

我遇到了类似的问题并试图用代码描述它,因为它更容易解释。

基本上我有一个泛型集合,所以无论它实例化的集合类型如何,它都会有一些共同的属性和事件。我对这些常见属性感兴趣。

说,我有通用集合的实例化对象 - 获取这些属性和订阅事件的最佳方法是什么?我知道我可以通过实现一个接口并将其转换为接口定义来实现它,但我不喜欢这样做,因为我只是为了满足一个要求。有没有更好的方法来重构这个?

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;
    }
}

3 个答案:

答案 0 :(得分:3)

您可以将方法设为通用:

static string GetDetail<T>(MyList<T> myList)
{
    return myList.Detail;
}

这将允许您使用已编写的相同代码调用它,并完全消除界面。


编辑以回应评论:

鉴于您不知道类型,并且您只是检查object,看起来界面似乎是最好的方法。通过提供通用界面,您可以公开所需的所有成员,无论集合中包含哪些内容,都可以提供正确的行为。

答案 1 :(得分:2)

使您的GetDetail方法通用:

static string GetDetail<T>(MyList<T> list)
{
    return list.Detail;
}

答案 2 :(得分:1)

编辑:我认为可能涉及多个集合类。如果实际上只有一个类 - MyList<T> - 那么使用泛型方法绝对是正确的方法。

  

据我所知,我可以通过实现一个接口并将其转换为接口防御来实现,但我不喜欢它,因为我只是为了满足一个要求。

你这样做是为了表达收藏品的共同点。除非普通成员正在实现一个接口,否则它们恰好具有相同的名称 - 界面显示它们具有相同的含义

使用界面是正确的方法 - 但不清楚为什么你的GetDetail方法不仅仅将接口作为参数...假设你需要这个方法。