代码之家  ›  专栏  ›  技术社区  ›  myermian

C#:获取参数所属的类型

c#
  •  1
  • myermian  · 技术社区  · 15 年前
    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)?

    3 回复  |  直到 15 年前
        1
  •  2
  •   Jon Skeet    15 年前

    this -它已经是一个实例方法。

    只需使用:

    Type t = this.GetType();
    

    这将给 实际的 车辆类型,而不是 Vehicle .

        2
  •  1
  •   Jerod Houghtelling    15 年前

    你可以打电话 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); } 
        } 
    } 
    
        3
  •  0
  •   Paul Ruane    15 年前

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