C#: Get the Type that the parameter belongs to
public abstract class Vehicle
{
protected void Some开发者_JS百科Method<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?
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.
You don't need to pass in this
- it's already an instance method.
Just use:
Type t = this.GetType();
That will give the actual type of vehicle, not Vehicle
.
You can call GetType()
which will operate on the current instance. 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.
public class Car : Vehicle
{
private String _model;
public String Model
{
get { return _model; }
set { SomeMethod("Model", ref _model, value); }
}
}
Make SomeMethod
non-generic and then Type t = this.GetType()
.
精彩评论