[英]C# Generics Question
是否可以在c#中执行以下操作? 基本上TParent和TChildren应该是A类的类型,但不一定要有相同类型的传入。我知道这可能听起来令人困惑但我想强烈键入特定对象的子项和父项,但同时他们必须是同一类型。 因为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;
}
我希望这不会太混乱。 这是可能吗?
谢谢 :)
如果你试图说“父母必须将这种类型作为孩子,孩子必须将这种类型作为父母”,那么我认为答案是否定的,你不能,因为你也需要知道父母的父母和孩子的孩子的类型。
但是,你可以这样做
public interface IHasChildren<T>
{
List<T> Children { get; set; }
}
public interface IHasParent<T>
{
T Parent { get; set; }
}
public class A<TParent, TChildren> : IHasChildren<TChildren>, IHasParent<TParent>
where TParent : IHasChildren<A<TParent, TChildren>>
where TChildren : IHasParent<A<TParent, TChildren>>
{
public List<TChildren> Children { get; set; }
public TParent Parent { get; set; }
}
不,这是不可能的。 你最接近的是定义另一个基类型,并要求TParent和TChild继承:
public class A { } // or an interface
public class A<TParent, TChild> : A
where TParent : A
where TChild : A
{ }
这并不能保证TParent和TChild属于通用A<,>
类型,但至少允许您对它们施加一些约束, A<,>
实现可以采用这些约束。
不,这是不可能的。 但是,一种解决方法是创建A<TParent, TChild>
的子类,并强制泛型类型参数属于该类型:
public interface A
{
// some properties and methods
}
public class A<TParent, TChild> : A where TParent : A where TChild A
{
// something else here.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.