![](/img/trans.png)
[英]How can I return a new instance of a class as a string and use it as a parameter of a generic method?
[英]Why can't I return new instance of class specified in generic constraint
以下代碼無法編譯,因為“無法將表達式類型“ Response”轉換為返回類型“ T”
private T Test<T>() where T : SomeClass
{
return new SomeClass();
}
當您嘗試返回constaraint中指定的類的子類時,該錯誤表明是合理的,但此處的類型完全相同。 這種行為的原因是什么?
您無法按照描述的方式進行操作,因為如果您有派生類,例如
public class SomeDerivedClass : SomeClass
{
}
您的代碼正在有效地嘗試執行以下操作,這顯然是不正確的:
private SomeDerivedClass Test2()
{
return new SomeClass();
}
可以在方法return語句中返回類型T
,只需要向where子句添加一個new()
約束即可。
private T Test<T>() where T : SomeClass, new()
{
return new T();
}
您可以通過添加new()
約束然后創建T的實例來創建實例
private T Test<T>() where T : SomeClass, new()
{
return new T();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.