2011-08-30 49 views
3

我已經定義了一個彙編級屬性類FooAttribute這樣的:如何從程序集級屬性中引用私有類的類型?

namespace Bar 
{ 
    [System.AttributeUsage (System.AttributeTargets.Assembly, AllowMultiple=true)] 
    public sealed class FooAttribute : System.Attribute 
    { 
     public FooAttribute(string id, System.Type type) 
     { 
      // ... 
     } 
    } 
} 

,我用它來一個ID,關聯到類,例如:

[assembly: Bar.Foo ("MyClass", typeof (Bar.MyClass))] 

namespace Bar 
{ 
    public class MyClass 
    { 
     private class Mystery { } 
    } 
} 

這一切工作正常。但如果我需要以某種方式參考在MyClass中定義的私人類Mystery,該怎麼辦?這是可能嗎?試圖從頂級[assembly: ...]指令不起作用引用它,因爲類型是不公開可見:

[assembly: Bar.Foo ("Mystery", typeof (Bar.MyClass.Mystery))] // won't work 

,並試圖把[assembly: ...]指令到MyClass以便它可以看到Mystery是不合法的,如[assembly: ...]必須在頂層來定義:

namespace Bar 
{ 
    class MyClass 
    { 
     [assembly: FooAttribute (...)] // won't work either 
     ... 
    } 
} 

有通過聲明用戶組件的朋友訪問來自一個組件的外internal類型的方式,但如何關於在程序集內引用私有類型?我想這是不可能的,我只需要宣佈Mysteryinternal,但我想確保我沒有錯過一些微妙之處。

回答

2

您在上一段中的說法是正確的。您的選擇將是:

  • 使嵌套類內部,使typeof

  • 有一個額外的構造函數FooAttribute這需要私人嵌套的完全限定類型名稱類,然後使用反射來獲得代表它的System.Type

例如:

public sealed class FooAttribute 
{ 
    public FooAttribute(string id, string typeName) 
    { 
     var type = Type.GetType(typeName); 

     // whatever the other ctor does with the System.Type... 
    } 
} 

用法:

[assembly: Foo("Bar", typeof(Bar))] 
[assembly: Foo("Baz", "Foo.Bar+Baz, MyAssembly")] 

namespace Foo 
{ 
    public class Bar 
    { 
     private class Baz 
     { 
     } 
    } 
} 
+1

這應該是'Bar + Baz',而不是'Bar.Baz',當然? –

+0

斑點馬克!更新了答案 – MattDavey

4

使它internal(你已經聲明你不想做的)是最省力的方法。對於大多數代碼,允許MyClass公開(通過靜態屬性)類型實例(即public static Type MysteryType { get { return typeof(Mystery); } }將工作,但將不會工作從一個屬性(只有常數值的幾個基本類型可以使用。)

internal唯一的選擇,那麼,是把它譯碼成字符串文字(即[Foo("Bar.MyClass+Mystery")]),並使用typeof(MyClass).Assembly.GetType(fullName) - 但你失去了編譯器驗證該typeof通常提供(另請注意+運行時用來表示嵌套類型,而不是C#表示的.

就我個人而言,我只是把它做成internal

+0

非常感謝你對你的思念;可惜我不能接受這兩個答案... –

相關問題