Ste*_*ger 4 c# attributes guid const
如何在属性中使用静态Guid作为参数?
static class X
{
public static readonly Guid XyId = new Guid("---");
}
[MyAttribute(X.XyId)] // does not work
public class myClass
{
}
Run Code Online (Sandbox Code Playgroud)
它不起作用,因为Guid必须是readonly,它不能是const.string和byte []表示也是readonly.
这有什么解决方法吗?
这是不可能的,也永远不可能,因为[Attributes]
编译为元数据并且static
变量在运行时初始化,当然前者无法访问后者(通过Reflection除外).
如果标准
public const string MyGuid = "blah";
Run Code Online (Sandbox Code Playgroud)
不会对你有用,那么AFAIK是实现你想要的唯一方法,就是用Reflection.