简体   繁体   English

将属性设置为通用参数

[英]Set property to generic parameter

I have two classes Car and Truck , and they both extend my Vehicle class. 我有CarTruck这两个类,它们都扩展了Vehicle类。 Both Car and Truck have property that looks like this: CarTruck都具有如下所示的属性:

public int Wheels { get; set; }

Now, I have two methods which set the Wheels property to some variable. 现在,我有两种方法将Wheels属性设置为某个变量。 It looks like this: 看起来像这样:

public void SetCarWheels(int value)
{
     Car.Wheels = value;
}

public void SetTruckWheels(int value)
{
     Truck.Wheels = value;
}

Because the methods do the same thing, I wanted to make a method which would have an input parameter of type Vehicle . 由于这些方法具有相同的作用,因此我想制作一个输入参数类型为Vehicle The method should basically do this: 该方法基本上应该这样做:

public static void SetWheels<T>(Vehicle item, int wheels) where T : Vehicle
    {
        if (item!= null)
        {
            item.Wheels = wheels;
        }
    }

The problem is, it doesn't recognize the Wheels property. 问题是,它无法识别Wheels属性。

How can I solve this by using generics? 如何使用泛型解决此问题?

Please don't suggest alternative solutions without generics (I know that Car and Truck can have a const value of wheels, but for the sake of the problem let's leave this as it is). 请不要提出没有泛型的替代解决方案(我知道“ Car和“ Truck的车轮可以具有恒定的值,但是出于问题的考虑,让我们将其保持不变)。

Your code will only work if the property is an instance property in the Vehicle base class: 仅当该属性是Vehicle基类中的实例属性时,您的代码才有效:

public class Vehicle
{
    public int Wheels { get; set; }
}

Also, in your method you don't seem to use the generic type parameter and the variable: 另外,在您的方法中,您似乎没有使用泛型类型参数和变量:

public static void SetWheels<T>(T item, int wheels) where T : Vehicle
{
    if (item != null)
    {
        item.Wheels = wheels;
    }
}

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

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