簡體   English   中英

C#接口指定泛型返回類型

[英]C# interface specfying a generic return type

我有類似的東西:

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();
}

如果只有方法需要通用:

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

Tadaa :)!

或者,您可以只返回System.Object並將其轉換為您想要的任何內容。

如果您不希望整個界面(IExample)是通用的,那么您也可以這樣做

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM