我知道不可能从泛型类型参数继承,但是在为抽象类型的衍生物实现公共代理时它会很方便:-)
有谁知道为什么这是不可能的?
示例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
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:一些代码来说明如何使用它的示例.考虑以下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 …Run Code Online (Sandbox Code Playgroud) 我一直在感觉我的方式围绕C#编译器,它的限制是"继承的实例化泛型类".
无论如何,这是我的测试用例:
class Program
{
static void Main(string[] args)
{
var x = new InClass();
Console.WriteLine(x.Test(10)); //prints foo
Console.ReadLine();
}
}
class BaseClass<Foo, Bar>
{
public virtual Foo Test(Bar b)
{
return default(Foo);
}
public virtual string Test(int b)
{
return "foo"; ;
}
}
class InClass : BaseClass<string, int>
{
/*public override string Test(int b)
{
return "bar";
}*/
}
Run Code Online (Sandbox Code Playgroud)
我认为InClass的这个声明会抛出一个编译错误,因为它Test含糊不清.它也使得非泛型Test不可能在内部调用InClass.请注意我也有一些代码注释掉了InClass.如果我取消注释该代码,我会收到编译器错误.
是否在C#规范中提到了这种行为,或者这是闻所未闻的边缘情况?