在C#4.0中,是否可以从泛型类型参数派生类?

问题描述 投票:22回答:3

我一直在尝试这个,但我似乎无法弄清楚这一点。我想做这个...

public abstract class SingletonType<TSingleton, TBaseClass> : TBaseClass
    where TSingleton : TBaseClass, new()
    where TBaseClass : class
{
    static TSingleton _singleton;
    public static TSingleton Singleton
        => _singleton ?? (_singleton = new TSingleton());
}

计划是像这样使用它,它可以在基类周围“包裹”单例模式......

public class SingletonFoo : SingletonType<SingletonFoo, Foo> {
}

但是,我一直这样做

无法从'TBaseClass'派生,因为它是一个类型参数

嗯......我认为类型正是你从中得到的!

那我错过了什么?

注意:这当然是一个简单的例子,因为它没有添加任何有用的东西,但是假设SingletonType有很多其他与问题无关的逻辑,因此忽略了专注于手头的问题。

c# generics inheritance subclass derived-class
3个回答
18
投票

不,这是不可能的。例如,采用声明为sealed的类型。你不能从该类继承,并且没有约束限制非密封类型,ergo试图通过泛型参数继承它是不可能的。


25
投票

C#中的泛型类型不是C ++模板;请记住,泛型类型必须适用于所有可能的类型参数。模板只需要适用于您实际构建的结构。

这个问题是重复的;看到我的回答

Why cannot C# generics derive from one of the generic type parameters like they can in C++ templates?

对此更多的想法。基本上,简短的回答是,相当大的成本并没有超过该功能的小优势。如果你不喜欢这个答案,请看我的第二个答案:

Why cannot C# generics derive from one of the generic type parameters like they can in C++ templates?

如果您不喜欢该答案,请参阅后续问题:

What are the good reasons to wish that .NET generics could inherit one of the generic parameter types?


1
投票

即使涉及泛型,每种类型也只有1个真正的离散父类。即使在处理开放泛型类型(例如,typeof(List<>))时,您仍然可以找到父类。

如果你想要的是允许的,那就不是真的,typeof(SingletonType<,>不会有父类型,这是不允许的。


0
投票

不,这是不可能的,因为假设你有这个课程:

class bar {
  int example = 0;
}

现在这是我们的类型参数类:

class foo<T> : T {
  int example = 5;
}

如果我们创建了一个foo<bar>类型的变量,那么example会混淆。

© www.soinside.com 2019 - 2024. All rights reserved.