![](/img/trans.png)
[英]c# - what collection type is recommended for self-referential many-to-many model?
[英]Self-referential enum attributes in a C# dynamic assembly
請考慮以下代碼:
[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。
嘗試調用CreateType
調用之前SetCustomAttribute
(見示例代碼SetCustomAttribute
)。
Type created = eb.CreateType();
eb.SetCustomAttribute(new CustomAttributeBuilder(
typeof(TransitionToAttribute).GetConstructors().First(),
new object[] { Enum.Parse(created, "A") }));
你是對的,ESRogs,用於在枚舉上設置屬性。 但我還需要在枚舉文字(fb)上設置一個屬性。
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") }));
第一次調用SetCustomAttribute成功。 第二個失敗,出現InvalidOperationException:創建類型后無法更改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.