gpt4 book ai didi

c# - 获取属于特定开放泛型类型的类的所有属性

转载 作者:太空宇宙 更新时间:2023-11-03 22:49:09 27 4
gpt4 key购买 nike

如果我有以下泛型类:

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

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

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));

最佳答案

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

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

关于c# - 获取属于特定开放泛型类型的类的所有属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48344239/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com