c# - 如何获取未知列表类型(列表)
问题描述
我有一个方法可以获取类型为 T“GetPropertiesInfor() where T : new()”的所有属性,但是如果 TI 中有一个列表,则无法在列表中获取 UnknowType 的 PropertyInfor。
为此,我目前正在互联网上寻找解决方案,但我不知道我的搜索关键字是否正确。
这是我的方法:
//Get ProperTyInfor of a type T
public void GetPropertiesInfor<T>() where T : new()
{
T obj = new T();
List<PropertyInfo> mpropertyInfos =
obj.GetType().GetProperties().ToList();
for (int i=0;i< mpropertyInfos.Count;i++)
{
Console.WriteLine("property type ["+ i + "] = "
+ mpropertyInfos[i].PropertyType);
//If property i of T is type of List
if(typeof(IEnumerable).IsAssignableFrom(mpropertyInfos[i].PropertyType))
{
//now I know this property mpropertyInfos[i] is type of list
//how can I get PropertyInfor of Items in the list
}
}
}
如果 mpropertyInfos[i] 是一种列表,我想获取列表将存储的项目的所有 PropertyInfor。
解决方案
基本上你需要做的就是type.GetGenericArguments()[0]
假设你只有一个参数(就像一个列表一样)
if(typeof(IEnumerable).IsAssignableFrom(mpropertyInfos[i].PropertyType)))
var genericParam = mpropertyInfos[i].PropertyType.GetGenericArguments()[0];
返回表示封闭泛型类型的类型参数或泛型类型定义的类型参数的 Type 对象数组。
推荐阅读
- python - 日期更改时如何触发功能?
- php - laravel,用不同的过滤器过滤多对多的关系
- python-3.x - [Python]; 如何在 csv 文件中写两个变量,在同一行但不同的列
- reactive-programming - 当错误出现在 200 状态码的有效负载中时抛出错误
- php - 如何在 PHP 中随机化 JSON 数组?
- flutter - 颤振加载图像资产太慢
- python - 如何根据另一个列表对一个列表进行排序?
- rust - 替换std::sync::Semaphore,因为它已被弃用?
- python - 使用 json 将语音直接发送到文本输出到数据库
- c++ - clang 是否有权使用 std::void_t 给出此部分专业化的重新定义错误?