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

7

我希望创建一个类,该类具有一个泛型类型参数,该参数有一个约束条件,即必须是另一个泛型类的子类。

例如:

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个回答

2
我不认为这是可能的。这个问题 解决了同样的情况。 MSDN 中的这段文字也说明了它是不允许的,不像在 C++ 中。我不确定这个限制是否有原因。

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

我认为你需要重新设计你的类来使用一个泛型 object,或者只是接受重复的类型参数。

-2

这个代码是否能够正常工作或者符合你的需求?

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

不,TGeneric是一个类型参数而不是一个通用类型本身,但是是的,那正是我想要实现的。 - Kenneth
我认为在不先声明“T”的情况下,无法实现您想要的功能。泛型类型参数有点像函数参数;您必须在使用它们之前先声明它们。 - Craxal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接