【问题标题】:Generic type arguments inside generic constraints [duplicate]泛型约束内的泛型类型参数
【发布时间】:2016-08-20 07:53:24
【问题描述】:

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

例子:

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

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

【问题讨论】:

    标签: c# generics


    【解决方案1】:

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

    来自MSDN 的这个简介还声明它是不允许的,这与 C++ 不同。我不确定这种限制是否有原因。

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

    我认为您将不得不以某种方式重新设计您的类以使用通用 object,否则就只能使用重复的类型参数。

    【讨论】:

      【解决方案2】:

      这是否有效,甚至类似于您想要的?

      public SomeClass<TGeneric<T>> where TGeneric<T> : SomeGeneric<T>
      

      【讨论】:

      • 不,TGeneric 是一个类型参数本身不是泛型类型,但是是的,这就是我想要实现的目标
      • 我认为没有先声明T 就可以做你想做的事。泛型类型参数有点像函数参数。您必须先声明它们才能使用它们。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-16
      • 2017-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多