简体   繁体   English

如何使用泛型方法访问基类实例的派生类属性

[英]How to access the derived class properties from base class instance using generic method

I am trying to access all the properties of my derived class through base class reference variable. 我试图通过基类引用变量访问派生类的所有属性。

Classes 班级

        public class vehicle
        {
            public int ID { get; set; }
        }

        public class Car : vehicle
        {
            public string type  { get; set; }
            public string Name { get; set; }
        }

Here is the main in Main class 这是主班的主要课程

public static void saveCar<T>(T vehicle) where T : vehicle
        {
            //TODO : here I need to access all the propertie values but I dunno how access only derived class values             


        }

I am trying to do this way 我正在尝试这样做

static void Main(string[] args)
        {

            Car cr = new Car
            {
                ID = 1,
                type = "car",
                Name = "Maruthi"
            };
            saveCar<Car>(cr);            


        }

You can't really ask for T and know your real properties. 您不能真正要求T并知道您的不动产。
I think you should change your design to something like this: 我认为您应该将设计更改为以下内容:

    public abstract class Vehicle
    {
        public int Id { get; set; }

        public virtual void SaveCar()
        {
            // save Id
        }
    }

    public class Car : Vehicle
    {
        public string Type  { get; set; }
        public string Name { get; set; }

        public override void SaveCar()
        {
            base.SaveCar();
            // Save type & name
        }
    }

Why do you have saveCar as a generic method? 为什么将saveCar作为通用方法? If the saveCar method is a virtual method on Vehicle you can override and have the required extended save functionality in each derived type. 如果saveCar方法是Vehicle上的虚拟方法,则可以在每种派生类型中覆盖并具有所需的扩展保存功能。 However if you require an external method to handle actions such as save and have Vehicle and its derived classes as simple data representations, you will need to inspect the object and act accordingly. 但是,如果您需要外部方法来处理诸如save的操作,并将Vehicle及其派生类作为简单的数据表示形式,则需要检查对象并采取相应的措施。 Some like: 像:

    public static void saveCar(Vehicle vehicle)
    {
        if (vehicle != null)
        {
            Console.WriteLine(vehicle.ID);
            if (vehicle is Car)
            {
                var car = vehicle as Car;
                Console.WriteLine(car.Name);
            }
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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