[英]Set custom attribute value from Enum in C#
I have one custom attribute like below,我有一个自定义属性,如下所示,
[AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = false)]
public class SetValForAll : Attribute
{
public string Limit { get; set; }
public SetValForAll(string limit)
{
Limit = limit;
}
}
While using this attribute(SetValForAll) I want to pass the value of Limit using one Enum but it is showing error 'An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type'使用此属性(SetValForAll)时,我想使用一个枚举传递Limit的值,但它显示错误“属性参数必须是属性参数类型的常量表达式、typeof 表达式或数组创建表达式”
My Enum is like below,我的枚举如下所示,
public enum LimitEnum
{
max,
min
}
The below piece of code is throwing error in the attribute line.下面的代码在属性行中抛出错误。
[SetValForAll(LimitEnum.max.ToString())]
public class UsingTheAttributeHere
{
}
How I can take value from LimitEnum while using SetValForAll attribute, rather than passing hardcoded string?如何在使用SetValForAll属性时从 LimitEnum 中获取值,而不是传递硬编码字符串?
Well, you can't pass non-constant strings in attribute values.好吧,您不能在属性值中传递非常量字符串。 Why don't you use your
enum
type instead of string
for your property?为什么不使用
enum
类型而不是string
作为属性? You can use LimitEnum
to pass in the constructor.您可以使用
LimitEnum
传入构造函数。
[AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = false)]
public class SetValForAll : Attribute
{
public LimitEnum Limit { get; set; }
public SetValForAll(LimitEnum limit)
{
Limit = limit;
}
}
and use it like this:并像这样使用它:
[SetValForAll(LimitEnum.max)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.