1

我有一种情况,我需要获取应用于类的属性(装饰器)的属性值。那个被装饰的类是从一个抽象类继承的。正是这个抽象类需要获取属性信息,但它需要在静态函数内部进行。

我无法发布确切的场景,但这是一个没有属性的可怕示例,但请按原样使用:

public class VehicleShapeAttribute : Attribute
{
    public string Shape { get; }
    public VehicleShapeAttribute(string shape)
    {
        Shape = shape;
    }
}

public abstract class Vehicle
{
    public string Brand { get; set; }
    public string Model { get; set; }
    public string Colour { get; set; }

    public static string GetVehicleShape()
    {
        //return value from the attribute, from this static function. CANT DO THIS HERE
        return AnyInheritingClass.VehicleShapeAttribute.Shape;
    }
}

[VehicleShape("sedan")]
public class VauxhaulAstraSedan : Vehicle
{
    //calling GetVehicleShape() on this class should automatically return "sedan"
}

这可能吗?

这是一个不好的例子,但我无法发布实际代码

4

2 回答 2

2

使方法非静态并使用以下方法解析运行时类型this.GetType()

public abstract class Vehicle
{
    public string Brand { get; set; }
    public string Model { get; set; }
    public string Colour { get; set; }

    public string GetVehicleShape()
    {
        var attribute = Attribute.GetCustomAttribute(this.GetType(), typeof(VehicleShapeAttribute)) as VehicleShapeAttribute;

        if(attribute is VehicleShapeAttribute){
            return attribute.Shape;
        }

        return null;
    }
}

对于静态版本,您需要接受一个Vehicle参数,然后您可以检查其类型:

public static string GetVehicleShape(Vehicle vehicle)
{
    var attribute = Attribute.GetCustomAttribute(vehicle.GetType());
    // ...
于 2021-10-08T11:04:46.803 回答
2

或者(我只是在此处将 Mathias 的代码复制/粘贴到另一种语法形式中)如果您真的需要该方法static,因为您不想创建实例,您可以将以下方法添加到您的属性代码中(或任何其他静态类,但我喜欢将它与属性一起放在那里):

public static string GetFrom<T>()
{
    return GetFrom(typeof(T));
}

public static string GetFrom(Type t)
{
    var attribute = Attribute.GetCustomAttribute(t, typeof(VehicleShapeAttribute)) as VehicleShapeAttribute;

    if(attribute is VehicleShapeAttribute){
        return attribute.Shape;
    }

    return null;
}

然后你可以编写如下代码:

var shape = VehicleShapeAttribute.GetFrom<VauxhaulAstraSedan>();

或者

var shape = VehicleShapeAttribute.GetFrom(typeof(VauxhaulAstraSedan));

甚至

var vehicle = new VauxhaulAstraSedan();
var shape = VehicleShapeAttribute.GetFrom(vehicle.GetType());
于 2021-10-08T11:11:34.670 回答