简体   繁体   中英

How can I use Reflection to get all fields of particular interface type

Consider following interfaces

public interface ISample 
public interface ISample2 : ISample

public class A
{
    [Field]
    ISample SomeField {get; set;}

    [Field]
    ISample2 SomeOtherField {get; set; }
}

Suppose there are various classes like class A and various Fields like SomeField and SomeOtherField. How can I get a list of all such Fields which are of type ISample or other interfaces derived from ISample (like ISample2)

You can use a combination of Reflection and Linq to do something like this:

var obj = new A();
var properties = obj.GetType().GetProperties()
                    .Where(pi => typeof(ISample).IsAssignableFrom(pi.PropertyType))

You must be extra cautious when dealing with generics. But for what you ask this should be good

If you want to get all classes that have at least one property returning a child of ISample you will have to use assemblies, for instance, the Currently executing

Assembly.GetExecutingAssembly().GetTypes()
        .SelectMany(t => t.GetProperties().Where(pi => // same code as the sample above)

In case you have several assemblies to probe you can use something like this

IEnumerable<Assembly> assemblies = ....
var properties = assemblies
            .SelectMany(a => a.GetTypes().SelectMany(t => t.GetProperties()...))

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