[英]C# CodeDOM Enum value in CustomAttribute
I am trying to create a class with a custom attribute that looks like: 我正在尝试创建一个具有自定义属性的类,如下所示:
public class Head : Attribute
{
public Head(Permissions permission, int id)
{
Permission = permission;
Id = id;
}
public int Id { get; private set; }
public Permissions Permission { get; private set; }
}
where Permissions is an enum: 权限是枚举:
public enum Permissions { R, W, D, RW, RWD }
so when I generate the attribute: 所以当我生成属性时:
var head = new CodeAttributeDeclaration
{
Name = "Head",
Arguments =
{
new CodeAttributeArgument
{
Value = new CodePrimitiveExpression(Permissions.RWD)
},
new CodeAttributeArgument
{
Value = new CodePrimitiveExpression(idValue);
}
}
}
When I try to generate this I get ArgumentException and a hint of using CodeObjectCreateExpression, but since Attributes can only take constant values I wonder how this could be achieved? 当我尝试生成这个时,我得到ArgumentException和一些使用CodeObjectCreateExpression的提示,但由于Attributes只能采用常量值,我想知道如何实现这一点?
Try to write the code you want to generate: 尝试编写要生成的代码:
[Head(Permissions.RWD, 42)]
If you do that, you'll realize there is no "primitive expression" for enums, you need to write it as if you were accessing a static field: 如果你这样做,你会发现枚举没有“原始表达式”,你需要像访问静态字段一样编写它:
new CodeFieldReferenceExpression(
new CodeTypeReferenceExpression(typeof(Permissions)), "RWD")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.