简体   繁体   English

C#泛型问题

[英]C# Generics Question

Would it be possible to do something like the following in c#? 是否可以在c#中执行以下操作? Basically TParent and TChildren should be types of the class A but not necessairly have the same types that were passed in. I know this may sound confusing but I want to strongly type the children and parents of a particular object, but at the same time they must be of the same type. 基本上TParent和TChildren应该是A类的类型,但不一定要有相同类型的传入。我知道这可能听起来令人困惑但我想强烈键入特定对象的子项和父项,但同时他们必须是同一类型。 Because TParent inherits from A this would imply that it requires type parameters that inherit from A but using potentially different types. 因为TParent继承自A,这意味着它需要继承自A但使用可能不同类型的类型参数。

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

or more easily seen here: 或者更容易看到这里:

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

I hope this isn't too confusing. 我希望这不会太混乱。 Is this at all possible? 这是可能吗?

Thanks :) 谢谢 :)

If you're trying to say "The parent must have this type as a child and the child must have this type as a parent" then I think the answer is no, you can't, because you'd also need to know the type of the parent's parent and the child's child. 如果你试图说“父母必须将这种类型作为孩子,孩子必须将这种类型作为父母”,那么我认为答案是否定的,你不能,因为你也需要知道父母的父母和孩子的孩子的类型。

However, you can do this 但是,你可以这样做

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; }
}

No, this isn't possible. 不,这是不可能的。 The closest you can come is to define another base type, and require TParent and TChild to inherit from that: 你最接近的是定义另一个基类型,并要求TParent和TChild继承:

public class A { }  // or an interface

public class A<TParent, TChild> : A
  where TParent : A
  where TChild : A
{ }

Which doesn't guarantee you that TParent and TChild are of the generic A<,> type, but does at least allow you to place some constraints on them, which the A<,> implementation can take then assume. 这并不能保证TParent和TChild属于通用A<,>类型,但至少允许您对它们施加一些约束, A<,>实现可以采用这些约束。

No, this isn't possible. 不,这是不可能的。 One workaround, however, is to create a subclass of A<TParent, TChild> and enforce that the generic type parameters are of that type: 但是,一种解决方法是创建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.

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