指定通用返回类型的 C# 接口

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10147292/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 12:38:57  来源:igfitidea点击:

C# interface specfying a generic return type

c#genericsinterface

提问by River

I have something like:

我有类似的东西:

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

Is this possible???

这可能吗???

采纳答案by Femaref

If the whole interface should be generic:

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

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

If only the method needs to be generic:

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

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

回答by River

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

Tadaa :) !

多多 :) !

Or alternatively, you can just return System.Object and cast it to whatever you want.

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

回答by shankar_pratap

If you dont want the entire interface(IExample) to be generic, then you can do this too

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

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