【问题标题】:C# interface specfying a generic return type指定泛型返回类型的 C# 接口
【发布时间】:2012-04-13 19:41:44
【问题描述】:

我有类似的东西:

public interface IExample
{
  int GetInteger()
  T GetAnything(); //How do I define a function with a generic return type???
^^^^^
}

这可能吗???

【问题讨论】:

    标签: c# generics interface


    【解决方案1】:

    如果整个界面应该是通用的:

    public interface IExample<T>
    {
      int GetInteger();
      T GetAnything();
    }
    

    如果只有方法需要是通用的:

    public interface IExample
    {
      int GetInteger();
      T GetAnything<T>();
    }
    

    【讨论】:

    • +1。我完全忘记了该方法可以有自己的类型参数:)
    • 如果使用 .NET 4.0 最好尽可能使用协方差:公共接口 IExample, T GetAnything();
    • 那我该如何实现接口函数呢?
    • 请注意,如果接口作为一个整体是泛型的,实现它的类可能是具有相同类型参数的泛型类,或者必须显式地为它应该的任何类型实现接口支持。在前一种情况下,要拥有GetAnything 返回类型Foo,必须拥有ClassImplementingIExample&lt;Foo&gt;
    【解决方案2】:
    public interface IExample<T>
    {
       int GetInteger()
       T GetAnything();
    }
    

    多达 :) !

    或者,您可以直接返回 System.Object 并将其转换为您想要的任何内容。

    【讨论】:

    • 这很丑 - return System.Object and cast it to whatever you want.
    • 别以为他在问这个
    【解决方案3】:

    如果您不希望整个界面(IExample)是通用的,那么您也可以这样做

    public interface IExample
    {
      int GetInteger();
      T GetAnything<T>();     
    }
    

    【讨论】:

    • 只是为了澄清,如果你在接口中以这种方式声明方法,当你在实现接口的类上实现它时,你必须将它保留为泛型方法,你只会能够在调用从实现接口的类实例化的对象上的方法时指定其类型,而不是在类本身中
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-16
    • 1970-01-01
    • 2015-05-20
    • 1970-01-01
    • 1970-01-01
    • 2018-08-03
    相关资源
    最近更新 更多