简体   繁体   中英

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?

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); } 
    } 
} 

使SomeMethod为非泛型,然后Type t = this.GetType()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM