[英]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); }
}
}
Is it possible to do what I'm looking for... that is, get t be typeof(Car) or typeof(Plane) using the referenced parameter myParam somehow? 是否可以做我要寻找的...就是以某种方式使用引用的参数myParam获得typeof(Car)或typeof(Plane)?
Oh, and I would like to avoid having to pass in a 'this' instance to SomeMethod or adding another Generic constraint parameter if I can. 哦,如果可以的话,我想避免将'this'实例传递给SomeMethod或添加另一个Generic约束参数。
You don't need to pass in this
- it's already an instance method. 您不需要传递this
-它已经是一个实例方法。
Just use: 只需使用:
Type t = this.GetType();
That will give the actual type of vehicle, not Vehicle
. 这将给出车辆的实际类型,而不是Vehicle
。
You can call GetType()
which will operate on the current instance. 您可以调用将在当前实例上运行的GetType()
。 It's a little misleading because the code lives in the base class, but it will correctly get the inherited class type for you at runtime. 这有点误导,因为代码位于基类中,但是它将在运行时为您正确获取继承的类类型。
Type t = this.GetType();
/*or equivlently*/
Type t = GetType();
On a side note you don't have to pass the type into SomeMethod
it will be infered for you by the compiler. 另外,您不必将类型传递给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.