Skip to main content
 首页 » 编程设计

C#泛型问题

2024年02月24日23lidabo

是否可以在 C# 中执行类似以下操作? 基本上 TParent 和 TChildren 应该是 A 类的类型,但不是 necessairly 具有传入的相同类型。我知道这听起来可能令人困惑,但我想强类型化特定对象的子项和父项, 但同时它们必须属于同一类型。因为 TParent 继承自 A,这意味着它需要继承自 A 但可能使用不同类型的类型参数。

public class A<TParent, TChildren>  
    where TParent : A 
    where TControls : A 
{ 
    TParent Parent; 
    List<TChildren> Children; 
} 

或在这里更容易看到:

public class A<TParent, TChildren> 
    where TParent : A<?, ?> 
    where TChildren : A<?, ?> 
{ 
    TParent Parent; 
    List<TChildren> Children; 
} 

我希望这不会太困惑。这有可能吗?

谢谢:)

请您参考如下方法:

不,这是不可能的。最接近的方法是定义另一个基类型,并要求 TParent 和 TChild 继承自该基类型:

public class A { }  // or an interface 
 
public class A<TParent, TChild> : A 
  where TParent : A 
  where TChild : A 
{ } 

这不能保证 TParent 和 TChild 是通用的 A<,>类型,但至少允许您对它们施加一些限制,即 A<,>实现可以采取然后假设。