2011-06-09 68 views
2

也許這個問題讓你迷惑,但請幫我如何取消引用類型的對象轉換爲實際的對象

在.NET 4.0中,C#語言

我有兩個項目,一個是圖書館爲類定義類和屬性標記infors,其中一個是處理從庫中聲明的類的反射的項目。

問題是,沒有引用庫,我只是使用反射相關的類來讀取程序集,我必須獲得在對象類中聲明的屬性的值。

例如

---在LIB項目,名爲lib.dll

public class MarkAttribute: Attribute 
{ 
    public string A{get;set;} 
    public string B{get;set;} 
} 

[Mark(A="Hello" B="World")] 
public class Data 
{ 
} 

---反射項目

public void DoIt() 
{ 
    string TypeName="Lib.Data"; 
    var asm=Assembly.LoadFrom("lib.dll"); 
    foreach (var x in asm.GetTypes()) 
    { 
     if (x.GetType().Name=="Data") 
     { 
     var obj=x.GetType().GetCustomAttributes(false); 

     //now if i make reference to lib.dll in the usual way , it is ok 
     var mark=(Lib.MarkAttribute)obj; 
     var a=obj.A ; 
     var b=obj.B ; 

     //but if i do not make that ref 
     //how can i get A,B value 
     } 
    } 
} 

任何想法讚賞

回答

2

您可以使用反射,以及檢索屬性的屬性:

Assembly assembly = Assembly.LoadFrom("lib.dll"); 
Type attributeType = assembly.GetType("Lib.MarkAttribute"); 
Type dataType = assembly.GetType("Lib.Data"); 
Attribute attribute = Attribute.GetCustomAttribute(dataType, attributeType); 
if(attribute != null) 
{ 
    string a = (string)attributeType.GetProperty("A").GetValue(attribute, null); 
    string b = (string)attributeType.GetProperty("B").GetValue(attribute, null); 
    // Do something with A and B 
} 
+0

它的工作,我卡在getType,我差點忘了getProperty方法,它很糟糕 – simpleman 2011-06-09 06:25:45

2

你可以調用屬性的獲取者:

var attributeType = obj.GetType(); 
var propertyA = attributeType.GetProperty("A"); 
object valueA = propertyA.GetGetMethod().Invoke(obj, null) 
+0

太感謝你了 – simpleman 2011-06-09 06:24:47

3

如果您知道屬性的名稱,你可以使用dynamic,而不是反思:

dynamic mark = obj; 
var a = obj.A; 
var b = obj.B; 
+0

太感謝你了,動態關鍵字是新的概念,我^^ – simpleman 2011-06-09 06:23:28

1

您需要刪除許多GetTypes()的電話,因爲你已經有一個類型的對象。然後,您可以使用GetProperty來檢索自定義屬性的屬性。

foreach (var x in asm.GetTypes()) 
{ 
    if (x.Name=="Data") 
    { 
     var attr = x.GetCustomAttributes(false)[0]; // if you know that the type has only 1 attribute 
     var a = attr.GetType().GetProperty("A").GetValue(attr, null); 
     var b = attr.GetType().GetProperty("B").GetValue(attr, null); 
    } 
} 
+0

謝謝,你很好 – simpleman 2011-06-09 06:26:13

0
var assembly = Assembly.Load("lib.dll"); 
dynamic obj = assembly.GetType("Lib.Data").GetCustomAttributes(false)[0]; 
var a = obj.A; 
var b = obj.B; 
+0

謝謝你的幫助 – simpleman 2011-06-09 06:29:17

相關問題