【问题标题】:Members of interface's methods have different types接口方法的成员有不同的类型
【发布时间】:2010-01-16 22:13:16
【问题描述】:

我有这个界面

public interface TestInterface
{
   [returntype] MethodHere();
}

public class test1 : TestInterface
{
   string MethodHere(){
      return "Bla";
   }
}

public class test2 : TestInterface
{
   int MethodHere(){
     return 2;
   }
}

有没有办法让 [returntype] 动态化?

【问题讨论】:

    标签: c# interface types member


    【解决方案1】:

    要么将返回类型声明为 Object,要么使用泛型接口:

    public interface TestInterface<T> {
        T MethodHere();
    }
    
    public class test3 : TestInterface<int> {
       int MethodHere() {
          return 2;
       }
    }
    

    【讨论】:

      【解决方案2】:

      不是真正的动态,但你可以让它通用:

      public interface TestInterface<T>
      {
          T MethodHere();
      }
      
      public class Test1 : TestInterface<string>
      ... // body as before
      public class Test2 : TestInterface<int>
      ... // body as before
      

      如果这不是您所追求的,请详细说明您希望如何使用界面。

      【讨论】:

      • 谢谢,这正是我想要的!
      猜你喜欢
      • 2020-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-01
      相关资源
      最近更新 更多