[英]How to return the correct type of an inherited type from a method in C#?
下面是我想要實現的目標。 使用代碼片段更容易顯示。
abstract class MyBaseType {}
class MyType1: MyBaseType() {}
class MyType2: MyBaseType() {}
class MyType3: MyBaseType() {}
public class Utils()
{
public XXXX IdentifyCorrectType()
{
var identifyingCondition = GetCorrectType();// returns 1,2,3...
switch(identifyingCondition)
{
case 1:
return typeof(MyType1);break;
case 2:
return typeof(MyType2);break;
case 3:
return typeof(MyType3);break;
}
}
}
這段代碼在IdentifyCorrectType方法的聲明中應該寫什么來代替XXXX ? 返回值用於其他地方來實例化該類型,因此只需要從該方法返回正確的類型。
PS:由於類依賴性並不總是在任何地方都可用,因此無法返回所需類的對象(例如new MyType2()
)而不是類型。
編輯 1:根據@Cid
,根據評論更好的方法應該是:
public MyBaseType IdentifyCorrectType()
{
var identifyingCondition = GetCorrectType();// returns 1,2,3...
switch (identifyingCondition)
{
case 1:
return new MyType1();
case 2:
return new MyType2();
case 3:
return new MyType3();
default:
return null;
}
}
您可以使用Type 類作為 IdentificationCorrectType 方法的輸出:
public Type IdentifyCorrectType()
{
var identifyingCondition = GetCorrectType();// returns 1,2,3...
switch(identifyingCondition)
{
case 1:
return typeof(MyType1);
case 2:
return typeof(MyType2);
case 3:
return typeof(MyType3);
default:
return null;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.