C#动态程序集中的自引用枚举属性
考虑以下代码:C#动态程序集中的自引用枚举属性,c#,.net,enums,attributes,C#,.net,Enums,Attributes,考虑以下代码: [AttributeUsage(AttributeTargets.Field | AttributeTargets.Enum, AllowMultiple = true)] public class TransitionToAttribute : Attribute { public readonly object Next; public TransitionToAttribute(object next) {
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Enum, AllowMultiple = true)]
public class TransitionToAttribute : Attribute
{
public readonly object Next;
public TransitionToAttribute(object next)
{
Next = next;
}
}
[TransitionToAttribute(DirectedGraph.A)]
public enum DirectedGraph
{
[TransitionToAttribute(DirectedGraph.B)]
A,
[TransitionToAttribute(null)]
B
}
代码编译得很好。现在,我想在动态程序集中定义一个类似的枚举,代码如下:
AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly(
new AssemblyName("TestAssembly"), AssemblyBuilderAccess.RunAndSave);
ModuleBuilder mb = ab.DefineDynamicModule("TestModule");
EnumBuilder eb = mb.DefineEnum("DirectedGraph2", TypeAttributes.Public, typeof(int));
FieldBuilder fb = eb.DefineLiteral("A", 0);
FieldBuilder fb2 = eb.DefineLiteral("B", 1);
eb.SetCustomAttribute(new CustomAttributeBuilder(
typeof(TransitionToAttribute).GetConstructors().First(), new object[] { ??? }));
Type created = eb.CreateType();
我传递给属性构造函数的“?”是什么?“?”需要是我正在定义的枚举中“A”字面值的某种表示形式。我尝试过传递fb、fb.GetValue(null)并调用Enum.Parse()、Enum.ToObject()、Enum.GetValues()和其他方法的各种组合,但似乎没有任何效果
明显的替代品是???是基础整数枚举值(例如,0表示A,1表示B,等等),但这不是我需要的方式。在某个时刻,我想做一些类似的事情
TransitionToAttribute attr = GetCustomAttribute(...)
Type enumType = attr.Next.GetType();
并以此方式确定枚举类型。这在第一个通常编译的示例中是可能的。但是,如果我将基础枚举值传递给动态创建的属性,则类型信息将丢失,并且enumType报告为Int32。在调用
SetCustomAttribute
之前,请尝试调用CreateType
(有关详细信息,请参阅示例代码)
你说得对,ESRogs,它可以在枚举上设置属性。但是我还需要在enum literal(fb)上设置一个属性 对SetCustomAttribute的第一次调用成功。第二个失败,出现InvalidOperationException:创建类型后无法更改
Type created = eb.CreateType();
eb.SetCustomAttribute(new CustomAttributeBuilder(
typeof(TransitionToAttribute).GetConstructors().First(),
new object[] { Enum.Parse(created, "A") }));
Type created = eb.CreateType();
eb.SetCustomAttribute(new CustomAttributeBuilder(
typeof(TransitionToAttribute).GetConstructors().First(),
new object[] { Enum.Parse(created, "A") }));
fb.SetCustomAttribute(new CustomAttributeBuilder(
typeof(TransitionToAttribute).GetConstructors().First(),
new object[] { Enum.Parse(created, "A") }));