【问题标题】:C# Generics - Classes implementing other generic classesC# 泛型 - 实现其他泛型类的类
【发布时间】:2015-12-08 20:39:56
【问题描述】:

我有一个

public class A<T> where T : IBase
{
    //Does something
}

我需要第二个类,其行为类似于 A 类的集合

public class B<A<T>> : IEnumerable<A<T>> where T : IBase
{
}

问题是我不想创建类似的类

public class B<A<MyCustomObjectP>> : IEnumerable<A<MyCustomObjectP>>
{
}

public class C<A<MyCustomObjectQ>> : IEnumerable<A<MyCustomObjectQ>>
{
}

等等..我想让CustomObject成为实现IBase的泛型类型参数。

我发现即使这样做也是违法的:

public class B<T, U> : IEnumerable<T> where T : A<U> where U : IBase
{
}

如果这是非法的,我该如何实现这种行为?是否有更好的设计模式可能会有所帮助?

【问题讨论】:

    标签: c# generics


    【解决方案1】:

    IBase 约束是在A&lt;T&gt; 上定义的,因此必须在所有想要使用A&lt;U&gt; 的泛型类上再次定义它(使用UA&lt;T&gt; 类定义中的T 区分开来,但它可以被称为任何东西)。你应该能够简单地做:

    public class B<T> : IEnumerable<A<T>> where T : IBase { ... }
    

    【讨论】:

    • 嘿。那很简单。我想多了。谢谢!这似乎可以解决问题。 :)
    【解决方案2】:

    您写道,您需要 第二个类,其行为类似于 A 类的集合。

    由于您还有其他类(如B)继承自IBase,并且您想要添加这些类,您可以将集合设为IBase 的集合。

    因此解决方案看起来像这样(请注意,我使用了List,但您可以轻松地将其替换为IEnumerable - 但您必须自己实现.Add 之类的方法):

    void Main()
    {
        var items = new CollectionOf<IBase>(); // create list of IBase elements
        items.Add(new A() { myProperty = "Hello" }); // create object of A and add it to list
        items.Add(new B() { myProperty = "World" }); // create object of B and add it to list
        foreach(var item in items)
        {
            Console.WriteLine(item.myProperty);
        }
    }
    
    // this is the collection class you asked for
    public class CollectionOf<U>: List<U>
    where U: IBase
    {
        // collection class enumerating A
        // note you could have used IEnumerable instead of List
    }
    
    public class A: IBase
    {
        // class A that implements IBase
        public string myProperty { get; set; }
    }
    
    public class B: IBase
    {
        // class B that implements IBase too
        public string myProperty { get; set; }
    }
    
    public interface IBase {
        // some inteface
        string myProperty { get; set; }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多