简体   繁体   English

具有两种泛型类型的泛型类

[英]Generic class with two generic types

I have a generic class for "Selectable Items" which is useful for Lists. 我有一个“可选项”的泛型类,它对列表很有用。 Now I want a selectable item to include a list of other selectable items. 现在我想要一个可选项包括其他可选项的列表。 Here is my code: 这是我的代码:

public interface ISelectableItem<T>
{
    bool IsSelected { get; set; }
    bool IsVisible { get; set; }
    string DisplayName { get; set; }
    T Value { get; set; }
    ObservableCollection<ISelectableItem<T>> SubItems { get; }
}

For now the SubItems collection is of the same type as the SelectableItem itself. 目前, SubItems集合与SelectableItem本身的类型相同。

Question is: how do I have to declare this interface so that SubItems is also ISelectableItem , but of type T2 , not T ? 问题是:我如何声明这个接口,以便SubItems也是ISelectableItem ,但T2类型,而不是T

Add a second generic type, T2 , to the type definition: 将第二个泛型类型T2添加到类型定义中:

public interface ISelectableItem<T, T2>
{
    T Value { get; set; }
    ObservableCollection<ISelectableItem<T2>> SubItems { get; }
}

Plan B would be to deviate between the sub items and master items by adding a second interface layer: 计划B将通过添加第二个界面层来区分子项和主项:

public interface ISelectableItem<T, T2> : ISelectableItem<T>
{
    ObservableCollection<ISelectableItem<T2>> SubItems { get; }
}

public interface ISelectableItem<T>
{
    bool IsSelected { get; set; }
    bool IsVisible { get; set; }
    string DisplayName { get; set; }
    T Value { get; set; }
}

This would work for example: 这可以作为例如:

public class A : ISelectableItem<string> { ... }

public class B : ISelectableItem<string, string> { ... }

B b = new B();
b.SubItems.Add(new A());

Or even: 甚至:

b.SubItems.Add(new B());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM