[英]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.