简体   繁体   中英

Get all properties on a class that are a specific open generic type

If I have the following generic class:

public class Gen<T>
{
    public T Value { get; set; }
}

And a class that uses it:

public class Thing
{
    public Gen<int> GenIntProperty { get; set; }
    public Gen<string> GenStringProperty { get; set; }
    public string NoGenericProp { get; set; }
}

Using reflection, how can I get just the properties that are based on the open generic type Gen<T> , specifically GenIntProperty and GenStringProperty ?

I've tried various forms of this code, but I keep running in to errors like this due to not being able to reference the open generic type.

Using the generic type 'UserQuery.Gen' requires 1 type arguments

var genProps = typeof(Thing).GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(pi => pi.PropertyType == typeof(Gen));

You need to get the generic type definition of the property type and compare it with the open generic type :

var genProps = typeof(Thing)
    .GetProperties(BindingFlags.Public | BindingFlags.Instance)
    .Where(pi => pi.PropertyType.IsGenericType && pi.PropertyType.GetGenericTypeDefinition() == typeof(Gen<>));

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