[英]How to implement generic method in c#
請幫助我實現通用方法。 我收到此消息:
錯誤1'T'不包含'GetDetails'的定義,並且找不到擴展方法'GetDetails'接受類型為'T'的第一個參數(是否缺少using指令或程序集引用)
我在哪里弄錯了?
public static void displayAnimal<T>(ref T mammal)
{
T ourMammal;
ourMammal = mammal;
mammal.GetDetails();
}
由於T可以是任何類型,並且編譯器不知道此方法將獲得哪種類型,因此可以僅使用通用對象方法。 如果您需要使用某些類或接口的方法,則應指定“ where”(通用類型約束)
interface IAnimal // or class
{
/*return type*/ GetDetails();
}
public static void displayAnimal<T>(ref T mammal) where T :IAnimal
{
T ourMammal;
ourMammal = mammal;
mammal.GetDetails();
}
您的方法是通用的,因此編譯器不知道(在編譯時)哪種特定類型T
想象一下,我將這種方法稱為
int noGetDetails = 12;
displayAnimal(ref noGetDetails);
int
沒有GetDetails()
實現。
因此,有沒有辦法讓編譯器,以確定哪些mammal.GetDetails()
可能是,因為沒有用於定義類型mammal
。
您可以添加通用約束來強制T
為實現GetDetails()
方法的類型:
public class MammalBase
{
public void GetDetails() { return... }
}
public class YourClass
{
public static void displayAnimal<T>(ref T mammal) where T : MammalBase // this is the constraint
{
mammal.GetDetails();
}
}
where T : MammalBase
的約束告訴編譯器,只有從MammalBase
繼承的類型MammalBase
可以用作通用參數。 因此,編譯器知道mammal
實現了GetDetails()
方法。
請注意 ,您的代碼中沒有使用ref
關鍵字,並且您實際上不需要顯示的代碼泛型,因為您只需將參數類型MammalBase
(但也許您只是顯示了一個簡短的示例,並且需要ref
和泛型用於您的實際應用)。
如果您打算使用一組可能的類型,則還可以嘗試強制轉換通用類型並檢查其是否有效。
public static void displayAnimal<T>(T mammal)
{
TargetType targetMammal = T as TargetType;
if(targetMammal != null)
{
// the target type should have the function .GetDetails();
targetMammal.GetDetails();
}
}
如果您將其投放,intellisense會告訴您可以訪問哪些屬性和功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.