考虑以下代码:
[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() 和其他方法的各种组合,但似乎没有任何效果。
明显替代 ???是基础整数枚举值(例如,A 为 0,B 为 1,等等),但这并不像我需要的那样工作。在某些时候,我想做一些类似的事情
TransitionToAttribute attr = GetCustomAttribute(...)
Type enumType = attr.Next.GetType();
并以此方式确定枚举类型。这在第一个正常编译的示例中是可能的。但是,如果我将底层枚举值传递给动态创建的属性,类型信息将丢失并且 enumType 被报告为 Int32。
最佳答案
尝试在调用 SetCustomAttribute
之前调用 CreateType
(请参阅 SetCustomAttribute
的示例代码)。
Type created = eb.CreateType();
eb.SetCustomAttribute(new CustomAttributeBuilder(
typeof(TransitionToAttribute).GetConstructors().First(),
new object[] { Enum.Parse(created, "A") }));
关于c# - C# 动态程序集中的自引用枚举属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1392037/