是的你可以。
假设您有这样的字段类
public class Field
{
public string Property1{get;set;}
public int Property2 {get;set;}
}
和这样的十进制字段类
public class DecimalField:Field
{
public int DecimalFieldProperty {get;set;}
}
,和这样的Accountfield
public class AccountField:Field
{
public double Balance{get;set;}
}
,并假设您有一个名为 DoSomething 的方法,该方法需要一个Field类型的参数,如下所示
void DoSomething(Field field)
{}
然后要获取传入的具体类型,您可以执行类似的操作
void DoSomething(Field field)
{
var decimalField = field as DecimalField;
//Do something with the decimal field instance
if(decimalField !=null)
{
Console.WriteLine("Decimal Field Property {0}",decimalField .DecimalFieldProperty );
return;
}
//Cast the field as a account field instance
var accountField = field as AccountField;
if(accountField !=null)
{
Console.WriteLine("Balance {0}", accountField.Balance );
return;
}
//Do something else with the normal field
Console.WriteLine("Normal Field");
}