相关疑难解决方法(0)

对约束泛型类型参数的继承

我知道不可能从泛型类型参数继承,但是在为抽象类型的衍生物实现公共代理时它会很方便:-)

有谁知道为什么这是不可能的?

示例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# generics

27
推荐指数
2
解决办法
3万
查看次数

这种滥用泛型的方式如何不模糊/在编译器中触发错误

我一直在感觉我的方式围绕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#规范中提到了这种行为,或者这是闻所未闻的边缘情况?

.net c# generics specifications compiler-errors

4
推荐指数
1
解决办法
158
查看次数

标签 统计

c# ×2

generics ×2

.net ×1

compiler-errors ×1

specifications ×1