[英]C#: Get the Type that the parameter belongs to
public abstract class Vehicle
{
protected void SomeMethod<T>(String paramName, ref T myParam, T val)
{
//Get the Type that myParam belongs to...
//(Which happens to be Car or Plane in this instance)
Type t = typeof(...);
}
}
public class Car : Vehicle
{
private String _model;
public String Model
{
get { return _model; }
set { SomeMethod<String>("Model", ref _model, value); }
}
}
public class Plane: Vehicle
{
private Int32 _engines;
public In32 Engines
{
get { return _engines; }
set { SomeMethod<Int32>("Engines", ref _engines, value); }
}
}
是否可以做我要尋找的...就是以某種方式使用引用的參數myParam獲得typeof(Car)或typeof(Plane)?
哦,如果可以的話,我想避免將'this'實例傳遞給SomeMethod或添加另一個Generic約束參數。
您不需要傳遞this
-它已經是一個實例方法。
只需使用:
Type t = this.GetType();
這將給出車輛的實際類型,而不是Vehicle
。
您可以調用將在當前實例上運行的GetType()
。 這有點誤導,因為代碼位於基類中,但是它將在運行時為您正確獲取繼承的類類型。
Type t = this.GetType();
/*or equivlently*/
Type t = GetType();
另外,您不必將類型傳遞給SomeMethod
,編譯器會為您SomeMethod
該類型。
public class Car : Vehicle
{
private String _model;
public String Model
{
get { return _model; }
set { SomeMethod("Model", ref _model, value); }
}
}
使SomeMethod
為非泛型,然后Type t = this.GetType()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.