C# 如何通过反射使列表类型与示例元素类型一致?
我需要定义一种从服务接收的对象类型。服务有不同的名称空间,但对象相同,所以我编写了一些解析器来获取接收到的类型的名称。 但是我在检测嵌套列表类型时遇到了一些麻烦,比如C# 如何通过反射使列表类型与示例元素类型一致?,c#,generics,reflection,C#,Generics,Reflection,我需要定义一种从服务接收的对象类型。服务有不同的名称空间,但对象相同,所以我编写了一些解析器来获取接收到的类型的名称。 但是我在检测嵌套列表类型时遇到了一些麻烦,比如 List<List<SomeObjectType>> or List<List<Tuple<int,int,SomeObjectType>> 列表 或 列表0)//如果有泛型参数,则运行递归 { var listOfParams=新列表(); foreac
List<List<SomeObjectType>>
or
List<List<Tuple<int,int,SomeObjectType>>
列表
或
列表0)//如果有泛型参数,则运行递归
{
var listOfParams=新列表();
foreach(通用参数中的var gp)
{
Add(this.getType(gp,名称空间));
}
//这是问题的核心
如何添加通用参数(foundType、listOfParams);/????
}
返回类型;
}
}
可能吗?=) 看来你在寻找方法
谢谢正是我需要的!foundType=foundType.MakeGenericType(listOfParams.ToArray());
public Type getType(TypeSpec TypeInfo, string NameSpace)
{
Type foundType = ObjectsHelper.ByName(NameSpace + "." + nameOfType);
if (foundType == null) throw new TypeNotFoundException(TypeInfo.name);
else
{
if (TypeInfo.generic_params != null && TypeInfo.generic_params.Count > 0) // if has generic params, run recursive
{
var listOfParams = new List<Type>();
foreach (var gp in generic_params)
{
listOfParams.Add(this.getType(gp, NameSpace));
}
// here is a heart of the matter
HowToAddGenericParameters(foundType, listOfParams); // ????
}
return foundType;
}
}
foundType.MakeGenericType(listOfParams.ToArray());