【问题标题】:calling method in template in C#在C#模板中调用方法
【发布时间】:2012-12-20 10:46:41
【问题描述】:

我尝试使用模板方法 (foo1) 中的方法 (foo2),编译器说他不知道属于该类 (T) 的方法 (foo2)。

什么是正确的语法,哪个编译器接受它?

private void foo1<T>(T instance)
{
    instance.foo2();
}

【问题讨论】:

  • 什么是 C# 中的方法模板?
  • 这里必须使用泛型吗?你能传递某个类的接口,其中定义了foo2 吗?

标签: c#


【解决方案1】:

您应该像下面的代码 sn-p 那样对泛型类型创建约束:

private void foo1<T>(T instance) where T : IFoo
{ 
    instance.foo2(); 
}

interface IFoo
{
    void foo2();
}

其中定义了,closed generic types 只能从IFoo 接口派生。但是你为什么不坚持使用下面给出的非通用版本呢?

private void foo1(IFoo instance) 
{ 
    instance.foo2(); 
}

interface IFoo
{
    void foo2();
}

【讨论】:

    【解决方案2】:

    您使用的是泛型方法,对泛型类型没有任何限制。

    这意味着它可以是任何对象。编译器抱怨是因为大多数对象没有foo2 方法。

    如果您希望能够在泛型参数上调用该方法,则需要将泛型类型限制为具有foo2() 方法的类型。

    或者,不要使用泛型,而是传入定义了foo2 的抽象类型。

    【讨论】:

      猜你喜欢
      • 2013-03-07
      • 1970-01-01
      • 1970-01-01
      • 2011-05-18
      • 1970-01-01
      • 1970-01-01
      • 2014-03-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多