想做genericinterface 其中T: issomeingelse / /.实

本文关键字:this genericinterface 其中 想做 issomeingelse typeof | 更新日期: 2023-09-27 17:53:44

我想在我的通用接口的where限制中使用this关键字或typeof(this)之类的东西,但显然这是不正确的(既不编译)。有什么我不知道的巧妙方法吗?

interface IParent<TChild> where TChild : IChildOf<typeof(this)>
{
    void AddRange(TChild children){}
}
interface IChildOf<TParent> : IDisposable
{
    TParent Parent { get; }
}

还是

interface IParent<TChild, T2> where TChild : IChildOf<T2>

并且只知道T2将是实现接口的类?

想做genericinterface <T>其中T: issomeingelse <typeof(this)>/ /.实

这里可以使用奇怪的重复出现的通用模式:

interface IParent<TChild, TParent>
  where TChild : IChildOf<TParent>
  where TParent : IParent<TChild, TParent>
{
  void AddRange(TChild children);
}
但是我会认真考虑重新评估你的设计。你真的需要这个吗?

我想你唯一的选择是:

interface IParent<TChild, TParent> where TChild : IChildOf<TParent>
{
    void AddRange(TChild children);
}

您只能在泛型接口的类型约束中使用类型参数或已知的编译时类型,因此这是您能做的最好的事情。

似乎您想要构建一个每个节点有多个子节点的树结构。你可以这样做:

interface INode
{
    List<INode> Children { get; }
    void AddRange(IEnumerable<INode> children);
}
class Node : INode
{
    List<INode> Children { get; private set; }
    void AddRange(IEnumerable<INode> children)
    {
        Children.AddRange(children);
    }
}