在运行时决定自定义属性的值
Decide Value of custom attribute at runtime
我有以下场景:
/* Attribute to be filled */
public class Flower
{
public FlowerType Type { get; set; }
public string Value { get; set; }
}
public enum FlowerType
{
Rose,
Daisy,
Tulip
}
[AttributeUsage(AttributeTargets.Class)]
public sealed class FlowerAttribute : Attribute
{
public string FlowerValue { get; }
public FlowerAttribute(string flowerValue)
{
FlowerValue = flowerValue;
}
}
我想要实现的是一种根据运行时给 class Flower
属性的方法,这意味着如果花将被实例化为 Rose
类型,那么 Flower
顶部的属性会将 FlowerValue
设置为 "Rose"
。我能以某种方式实现这一目标吗?一如既往地提前致谢!
Can I achieve this somehow?
没有。属性参数总是在编译时决定——这就是为什么它们必须是编译时常量。这些值被烘焙到 IL 中。
不清楚这里的更大目标是什么,但是任何 动态 都不太可能适合属性。
我有以下场景:
/* Attribute to be filled */
public class Flower
{
public FlowerType Type { get; set; }
public string Value { get; set; }
}
public enum FlowerType
{
Rose,
Daisy,
Tulip
}
[AttributeUsage(AttributeTargets.Class)]
public sealed class FlowerAttribute : Attribute
{
public string FlowerValue { get; }
public FlowerAttribute(string flowerValue)
{
FlowerValue = flowerValue;
}
}
我想要实现的是一种根据运行时给 class Flower
属性的方法,这意味着如果花将被实例化为 Rose
类型,那么 Flower
顶部的属性会将 FlowerValue
设置为 "Rose"
。我能以某种方式实现这一目标吗?一如既往地提前致谢!
Can I achieve this somehow?
没有。属性参数总是在编译时决定——这就是为什么它们必须是编译时常量。这些值被烘焙到 IL 中。
不清楚这里的更大目标是什么,但是任何 动态 都不太可能适合属性。