C# 调用泛型类的方法
以下是上下文: 我尝试编写一个映射程序,用于将DomainModel对象动态转换为ViewModel对象。我遇到的问题是,当我试图通过反射调用泛型类的方法时,我遇到了以下错误: System.InvalidOperationException:不能对ContainsGenericParameters为true的类型或方法执行后期绑定操作 有人能帮我找出毛病在哪里吗?我们将不胜感激 下面是代码(我试图简化它):C# 调用泛型类的方法,c#,.net,asp.net-mvc,generics,reflection,C#,.net,Asp.net Mvc,Generics,Reflection,以下是上下文: 我尝试编写一个映射程序,用于将DomainModel对象动态转换为ViewModel对象。我遇到的问题是,当我试图通过反射调用泛型类的方法时,我遇到了以下错误: System.InvalidOperationException:不能对ContainsGenericParameters为true的类型或方法执行后期绑定操作 有人能帮我找出毛病在哪里吗?我们将不胜感激 下面是代码(我试图简化它): 公共类映射类 { 公共字符串测试() { 回归试验 } 公共void MapClass
公共类映射类
{
公共字符串测试()
{
回归试验
}
公共void MapClassReflection(SourceType源,ref DestinationType目标)
{
类型sourceType=source.GetType();
类型destinationType=destination.GetType();
foreach(sourceType.GetProperties()中的PropertyInfo sourceProperty)
{
string destinationPropertyName=LookupForPropertyDestinationType(sourceProperty.Name,destinationType);
if(destinationPropertyName!=null)
{
PropertyInfo destinationProperty=destinationType.GetProperty(destinationPropertyName);
if(destinationProperty.PropertyType==sourceProperty.PropertyType)
{
destinationProperty.SetValue(目标,sourceProperty.GetValue(源,null),null);
}
其他的
{
d1型=类型(MapClass);
类型[]typeArgs={destinationProperty.GetType(),sourceType.GetType()};
构造的类型=d1.MakeGenericType(typeArgs);
对象o=Activator.CreateInstance(构造,空);
MethodInfo theMethod=d1.GetMethod(“测试”);
string toto=(string)method.Invoke(o,null);
}
}
}
}
私有字符串LookupForPropertyDestinationType(字符串源PropertyName,类型destinationType)
{
foreach(destinationType.GetProperties()中的PropertyInfo属性)
{
if(property.Name==sourcePropertyName)
{
返回sourcePropertyName;
}
}
返回null;
}
}
您需要对构造的类型constructed
调用GetMethod
,而不是对类型定义d1
调用
// ...
Type d1 = typeof(MapClass<,>);
Type[] typeArgs = { destinationProperty.GetType(), sourceType.GetType() };
Type constructed = d1.MakeGenericType(typeArgs);
object o = Activator.CreateInstance(constructed, null);
MethodInfo theMethod = constructed.GetMethod("Test");
string toto = (string)theMethod.Invoke(o, null);
// ...
/。。。
d1型=类型(MapClass);
类型[]typeArgs={destinationProperty.GetType(),sourceType.GetType()};
构造的类型=d1.MakeGenericType(typeArgs);
对象o=Activator.CreateInstance(构造,空);
MethodInfo theMethod=constructed.GetMethod(“测试”);
string toto=(string)method.Invoke(o,null);
// ...
@usr“调用泛型类的方法”与“调用类的泛型方法”不同,这里的答案无法解决问题。@MasonZhang重新打开。
// ...
Type d1 = typeof(MapClass<,>);
Type[] typeArgs = { destinationProperty.GetType(), sourceType.GetType() };
Type constructed = d1.MakeGenericType(typeArgs);
object o = Activator.CreateInstance(constructed, null);
MethodInfo theMethod = constructed.GetMethod("Test");
string toto = (string)theMethod.Invoke(o, null);
// ...