2011-06-09 69 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

相关问题