指定泛型返回类型的C#接口

指定泛型返回类型的C#接口,c#,generics,interface,C#,Generics,Interface,我有点像: public interface IExample { int GetInteger() T GetAnything(); //How do I define a function with a generic return type??? ^^^^^ } 这可能吗?公共接口示例 public interface IExample<T> { int GetInteger() T GetAnything(); } { int GetInteger()

我有点像:

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

公共接口示例
public interface IExample<T>
{
   int GetInteger()
   T GetAnything();
}
{ int GetInteger() 我什么也得不到; }
塔达:)


或者,您也可以只返回System.Object并将其强制转换为任何您想要的格式。

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

public interface IExample<T>
{
  int GetInteger();
  T GetAnything();
}
public interface IExample
{
  int GetInteger();
  T GetAnything<T>();
}
公共接口示例
{
int GetInteger();
我什么也得不到;
}
如果只有方法需要是泛型的:

public interface IExample<T>
{
  int GetInteger();
  T GetAnything();
}
public interface IExample
{
  int GetInteger();
  T GetAnything<T>();
}
公共接口示例
{
int GetInteger();
我什么也得不到;
}

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

public interface IExample
{
  int GetInteger();
  T GetAnything<T>();     
}
公共接口示例
{
int GetInteger();
我什么也得不到;
}

这太难看了-
返回系统。对象并将其转换为您想要的任何对象。
不要认为这是他要求的+1。我完全忘记了方法可以有自己的类型参数:)如果使用.NET4.0,最好使用协方差(如果可能的话):公共接口IExample,T GetAnything();那么我如何实现接口函数呢?请注意,如果接口作为一个整体是泛型的,那么实现它的类可能是具有相同类型参数的泛型类,或者必须显式地实现它应该支持的任何类型的接口。在前一种情况下,要使用
GetAnything
返回类型
Foo
,必须使用
ClassImplementingIExample
。如果在接口中以这种方式声明该方法,那么在实现该接口的类上实现该方法时,您必须将其保持为泛型方法,并且只有在从实现接口的类实例化的对象上调用方法时,才能指定其类型,而不是在类本身中