繁体   English   中英

获取特定开放泛型类的类的所有属性

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

如果我有以下泛型类:

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

还有一个使用它的类:

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

使用反射,我怎样才能得到一点是基于开放式泛型类型的属性Gen<T>特别是GenIntPropertyGenStringProperty

我已经尝试过各种形式的代码,但由于无法引用开放的泛型类型,我一直在运行这样的错误。

使用泛型类型“UserQuery.Gen”需要1个类型参数

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

您需要获取属性类型的泛型类型定义,并将其与开放泛型类型进行比较:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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