在约束泛型类型参数继承 [英] Inheritance on a constrained generic type parameter
问题描述
我知道这是不可能从一个泛型类型参数继承,但实施抽象类型的衍生品共同代理时,它会是得心应手: - )
I know it isn't possible to inherit from a generic type parameter, but it would be handy when implementing a common proxy for derivatives of an abstract type :-)
有谁知道这是为什么不可能?
Does anyone know why this isn't possible?
举例C#:
abstract class Foo
{
public virtual void Bar()
{
// nop
}
}
class FooProxy<TFoo> : TFoo
where TFoo : Foo
{
public override void Bar()
{
// do some stuff before
base.Bar();
// do some stuff after
}
}
编辑:一些更code来说明如何这可能是使用的例子。考虑美孚的下列衍生物:
Some more code to illustrate an example of how this could be used. Consider the following derivatives of Foo:
class FooX : Foo
{
public string X { get; set; }
public override void Bar()
{
Console.WriteLine("Doing Bar X");
}
}
class FooY : Foo
{
public string Y { get; set; }
public override void Bar()
{
Console.WriteLine("Doing Bar Y");
}
}
和调用code:
FooProxy<FooX> fooXProxy = new FooProxy<FooX>();
fooXProxy.X = "test X";
fooXProxy.Bar();
FooProxy<FooY> fooYProxy = new FooProxy<FooY>();
fooYProxy.Y = "test Y";
fooYProxy.Bar();
在code在酒吧()方法将使用FooX和FooY时可重复使用。的FooProxy覆盖
The code in the FooProxy override of Bar() method will be reused when using FooX and FooY.
编辑:修改为每皮特奥汉隆的回答:做酒吧()方法的虚拟
Revised as per Pete OHanlon's answer: made Bar() method virtual.
推荐答案
由于你不能。泛型不是模板。你不应该去想他们像C ++模板,并期望相同的行为。他们是根本不同的概念。
Because you can't. Generics are not templates. You shouldn't think about them like C++ templates and expect the same behavior. They are fundamentally different concepts.
C#的规范明确禁止的类型参数的用法为基类:
The C# specification explicitly prohibits usage of type parameters as base class:
一个类型参数不能直接用于声明一个基类(§10.2.4)或接口(§13.1.3)。
C# 3.0 Language Specification: Type Parameters (§4.5)
A type parameter cannot be used directly to declare a base class (§10.2.4) or interface (§13.1.3).
我明白你想要做的,它的用途是什么。这是C ++模板传统的用例。特别是,如果这是可以使用C#泛型之类的东西做的 起订量
库可以从中受益。问题是,C ++模板编译时查找和替换结构,而C#泛型是运行时间的事情。
Update:
I understand what you want to do and its use. This is a traditional use case of C++ templates. Specifically, if this was possible to do using C# generics, things like Moq
library could benefit from it. The problem is, C++ templates are compile time "find and replace" constructs while C# generics are a run time thing.
要证明这一事实,对于这个类:
To demonstrate this fact, for this class:
class Test<T> where T : class {
// whatever contents it might have...
}
只有一个IL将在编译时和运行时发出,JIT编译器会生成一个单本地code为所有参考类型的类型参数。这不是在所有的,其中本地code将发射用于每个 T
分别类似于C ++模板(这是受优化,但在概念上,他们是完全$的独立的部分C $ C)。
only a single IL will be emitted at compile time and at run time, the JIT compiler would generate a single native code for all reference-type type parameters. This is not like C++ templates at all, where native code would be emitted for every T
separately (it's subject to optimization but conceptually, they are completely separate pieces of code).
这篇关于在约束泛型类型参数继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!