2010-07-23 58 views
2

我有一個應用程序,需要在運行時加載DLL,我想在動態加載的DLL中創建一些自定義屬性,因此當它加載時,我可以檢查以確保某些屬性在嘗試使用它之前有一定的值。如何從運行時加載的DLL中檢索自定義屬性的值?

我創建這樣

using System; 
[AttributeUsage(AttributeTargets.Class)] 
public class ValidReleaseToApp : Attribute 
{ 
    private string ReleaseToApplication; 

    public ValidReleaseToApp(string ReleaseToApp) 
    { 
     this.ReleaseToApplication = ReleaseToApp; 
    } 
} 

在動態加載的DLL我設置的屬性這樣

[ValidReleaseToApp("TheAppName")] 
public class ClassName : IInterfaceName 
etc... etc.... 

的屬性,但是當我嘗試讀取屬性值我只得到屬性名稱「ValidReleaseToApp」如何檢索值「TheAppName」?

Assembly a = Assembly.LoadFrom(PathToDLL); 
Type type = a.GetType("Namespace.ClassName", true); 
System.Reflection.MemberInfo info = type; 
var attributes = info.GetCustomAttributes(true); 
MessageBox.Show(attributes[0].ToString()); 

更新:

因爲我動態在運行時加載的dll屬性的定義不利用。到主應用程序。所以,當我嘗試做了以下的建議

string value = ((ValidReleaseToApp)attributes[0]).ReleaseToApplication; 
MessageBox.Show(value); 

我得到這個錯誤

The type or namespace name 'ValidReleaseToApp' could not be found 

UPDATE2:

行,所以問題是,我的動態項目中定義的屬性加載的DLL。一旦我將屬性定義移動到它自己的項目中,並將該項目的引用添加到主項目和動態加載的dll中。建議的代碼起作用。

回答

4

這應該有效,我現在沒有在我面前的例子,但它看起來是正確的。基本上,你跳過了公開要訪問的屬性的步驟,並轉換爲屬性類型來檢索該屬性。

using System; 
[AttributeUsage(AttributeTargets.Class)] 
public class ValidReleaseToApp : Attribute 
{ 
    private string _releaseToApplication; 
    public string ReleaseToApplication { get { return _releaseToApplication; } } 

    public ValidReleaseToApp(string ReleaseToApp) 
    { 
     this._releaseToApplication = ReleaseToApp; 
    } 
} 


Assembly a = Assembly.LoadFrom(PathToDLL); 
Type type = a.GetType("Namespace.ClassName", true); 
System.Reflection.MemberInfo info = type; 
var attributes = info.GetCustomAttributes(true); 
if(attributes[0] is ValidReleaseToApp){ 
    string value = ((ValidReleaseToApp)attributes[0]).ReleaseToApplication ; 
    MessageBox.Show(value); 
} 
+0

的DLL有屬性的定義,而不是應用程序,我一從上面的代碼中調用它當我嘗試上面的代碼rec'd編譯錯誤「無法找到類型或名稱空間ValidReleaseToApp」如果我將Attrib def複製到調用應用程序中,我得到運行時錯誤無法投射類型爲'ValidReleaseToApp '鍵入'ValidReleaseToApp'。「任何想法? – etoisarobot 2010-07-23 16:12:18

+0

在這種情況下,您必須以獲得該屬性的相同方式獲取屬性的類型(你有'類型')。然後,而不是'是ValidReleaseToApp',我認爲你可以''typeof(attributeTypeFromAssembly)' – 2010-07-23 16:35:18

+0

感謝您的幫助,但如果我檢索這樣的類型「Type attrType = a.GetType(」ValidReleaseToApp「,true);」 如何使用它將對象轉換爲ValidReleaseToApp? – etoisarobot 2010-07-23 18:57:10

0

一旦你的自定義屬性,你可以將它們轉換爲屬性類的實例和訪問他們的proerties:

object[] attributes = info.GetCustomAttributes(typeof(ValidReleaseToAppAttribute), true); 
ValidReleaseToAppAttrigute attrib = attributes[0] as ValidReleaseToAppAttribute; 
MessageBox.Show(attrib.ReleaseToApp); 
相關問題