如何从Parent<;T父,T子>;

本文关键字:gt lt Parent | 更新日期: 2023-09-27 18:27:12

我有两个使用通用的接口

我的子界面看起来像:

public interface ICell<TContent>
{
    TContent Content { get; }
    string Background { get; }
    string Foreground { get; }
}

和我的家长界面类似:

public interface IRow<TRowHeader,TContent>
{
    TRowHeader RowHeader { get; }
    IList<ICell<TContent>> Zellen {get;}
}

当我创建一个基于IRow的类时,我必须设置我想要避免的TContent。所以我想知道如何从我的IRow中抽象出这个泛型?

最后我想能够写

public class MyCell : ICell<string>
{
    public string Background { get; set; }
    public string Content { get; set; }
    public string Foreground { get; set; }
}
public class MyRow: IRow<string,MyCell>
{
    public string RowHeader { get; set; }
    public IList<MyCell> Zellen { get; set; }
}

如何从Parent<;T父,T子>;

为了完成您的要求,您必须稍微更改IRow接口:

public interface IRow<TRowHeader, TCell>
{
    TRowHeader RowHeader { get; }
    IList<TCell> Zellen { get; }
}

现在的情况是,您需要确定IList可以容纳类型TCell。这里不能说TCellICell<T>(因为你必须在类型列表中定义T),但你可以添加另一个接口并这样做:

public interface ICell 
{ 
    string Background { get; }
    string Foreground { get; }
}
public interface ICell<TContent> : ICell
{
    TContent Content { get; }
}

这将允许您在IRow TCell类型上创建一个约束:

public interface IRow<TRowHeader, TCell> where TCell : ICell
{
    TRowHeader RowHeader { get; }
    IList<TCell> Zellen { get; }
}

现在,您可以定义您的MyRow

public class MyRow : IRow<string, MyCell>
{
    public string RowHeader { get; set; }
    public IList<MyCell> Zellen { get; set; }
}

并且约束条件都得到了满足。

这有点冗长,如果您可以放弃非泛型ICell,并指定ICell<T>,其中TIRow的约束中的任何类型,那就太好了,但在C#中,这是不可能的。

我的理解是:-单元格具有通用内容(TContent)-行是一个单元格列表(TCell)。TCell本身可以是通用的。

所以你的代码看起来像这样:

public interface ICell<TContent>
{
    TContent Content { get; }
    string Background { get; }
    string Foreground { get; }
}
public interface IRow<TRowHeader,TCell>
{
    TRowHeader RowHeader { get; }
    IList<TCell> Zellen {get;}
}

然后,

public class MyCell : ICell<string>
{
    public string Background { get; set; }
    public string Content { get; set; }
    public string Foreground { get; set; }
}
public class MyRow: IRow<string,MyCell>
{
    public string RowHeader { get; set; }
    public IList<MyCell> Zellen { get; set; }
}