简体   繁体   中英

.net 4.0 Reflection convert object to specific type

My problem is quite simple
Suppose I have those class:

public class A
{
    public Collection<B> B { get; set; }
    public Collection<C> C { get; set; }
}

public class B
{
    public int IntB { get; set; }
}

public class C
{
    public string StringC { get; set; }
}

And I write a function:

public void GetValue(string fieldName){
        A a = new A();
        PropertyInfo infor = typeof(A).GetProperty(fieldName);
        object obj = infor.GetValue(a,null);
}

My question is how can I turn obj to corresponding Collection, in this case is Collection<B> or Collection<C> , depending in fieldName value
Thank in advance

You can cast it:

var collection = (Collection<B>)(infor.GetValue(a,null));

EDIT:

if you use LINQ on the resulting collections, you may want to use OfType (link: http://msdn.microsoft.com/en-us/library/bb360913.aspx ) and/or Cast (link: http://msdn.microsoft.com/en-us/library/bb341406.aspx ) Like

var collection = getCollection(a,null));
collection.OfType<B>.Select(b => b.IntB)....

You can't have a statically typed object in your method when you determine the property that will be called at runtime. But the runtime time of obj is of the actual type of your property.

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