简体   繁体   中英

How to convert un-reference-type Object to actual object

Maybe this question make you confuse,but please help me

In .NET 4.0, language C#

I have two project,one is the library define classes and attribute mark infors for class, one is the project that process reflection of class declared from that library.

The problem is, without make reference to library, I just use reflection-related classes to read assembly and I have to get value of properties that declared in object class.

For example

---In LIB project, named lib.dll

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

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

---In Reflection project

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
      }
   }
}

any idea appreciated

If you know the names of the properties you could use dynamic instead of reflection:

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

You can invoke the getter of the property:

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

You can retrieve the attribute's properties using reflection as well:

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
}

You need to remove many of the GetTypes() calls, since you already have a Type object. Then you can use GetProperty to retrieve the property of the custom attribute.

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);
    }
}
var assembly = Assembly.Load("lib.dll");
dynamic obj = assembly.GetType("Lib.Data").GetCustomAttributes(false)[0];
var a = obj.A;
var b = obj.B;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM