C#:获取参数所属的Type

时间:2010-08-12 17:06:26

标签: c#

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约束参数。

3 个答案:

答案 0 :(得分:2)

您无需传递this - 它已经是实例方法。

只需使用:

Type t = this.GetType();

这将提供实际类型的车辆,而不是Vehicle

答案 1 :(得分:1)

您可以调用将在当前实例上运行的GetType()。这有点误导,因为代码存在于基类中,但它会在运行时为您正确地获取继承的类类型。

Type t = this.GetType(); 
/*or equivlently*/
Type t = GetType();

在旁注中,您不必将类型传递给SomeMethod,编译器会为您提供这些类型。

public class Car : Vehicle 
{ 
    private String _model; 
    public String Model 
    { 
        get { return _model; } 
        set { SomeMethod("Model", ref _model, value); } 
    } 
} 

答案 2 :(得分:0)

SomeMethod设为非通用,然后Type t = this.GetType()