泛型约束内的泛型类型参数

时间:2016-08-19 23:13:17

标签: c# generics

我想创建一个具有泛型类型参数的类,该类具有作为另一个泛型类的子类的约束。

示例:

public class SomeGeneric<T> where T : new()
{
    T CreateItem() => new T();
}

我要创建这个类。注意:我不希望此类的客户端指定内部类型参数两次:

public class TheClass<TGeneric> where TGeneric : SomeGeneric<T>, new()
{
    public T Item {get; private set;}
    public void TheClass
    {
        var instance = new TGeneric(); // this is possible because of the new() restriction
        Item = instance.CreateItem();
    }
}

然后可以按如下方式使用:

class AnotherClass
{

}

class Client : TheClass<SomeGeneric<AnotherClass>>
{
    public void SomeMethod()
    {
        var theInstanceOfAnotherClass = this.Item;
        // Do stuff with it
    }
}

据我所知,这是不可能的,因为它在这一行抱怨T未知:

public class TheClass<TGeneric> where TGeneric : SomeGeneric<T>, new()

解决方法如下:

public class TheClass<T, TGeneric> where TGeneric : SomeGeneric<T>, new()

但这意味着客户必须这样做:

public class Client : TheClass<AnotherClass, SomeGeneric<AnotherClass>>

我想避免重复内部类型参数。这可能吗?

2 个答案:

答案 0 :(得分:1)

我不认为这是可能的。 This question解决了同样的问题。

来自MSDN的这个模糊也表明它不允许,与C ++不同。我不确定是否有这种限制的原因。

  

在C#中,泛型类型参数本身不能是通用的,尽管构造的类型可以用作泛型。 C ++确实允许模板参数。

我认为你必须以某种方式重写你的类以使用泛型object,否则只需使用重复类型参数。

答案 1 :(得分:-1)

这是否有效甚至与您想要的相似?

public SomeClass<TGeneric<T>> where TGeneric<T> : SomeGeneric<T>
相关问题