11
這裏是上下文:調用通用類的方法
我嘗試編寫一個映射器來動態地將我的DomainModel對象轉換爲ViewModel Ojects。我得到的問題是,當我嘗試通過反射調用通用類的方法時出現此錯誤:
System.InvalidOperationException:對於ContainsGenericParameters爲true的類型或方法,無法執行後期操作。
有人可以幫我找出故障在哪裏嗎?這將不勝感激
這裏是代碼(我試圖簡化它):
public class MapClass<SourceType, DestinationType>
{
public string Test()
{
return test
}
public void MapClassReflection(SourceType source, ref DestinationType destination)
{
Type sourceType = source.GetType();
Type destinationType = destination.GetType();
foreach (PropertyInfo sourceProperty in sourceType.GetProperties())
{
string destinationPropertyName = LookupForPropertyInDestinationType(sourceProperty.Name, destinationType);
if (destinationPropertyName != null)
{
PropertyInfo destinationProperty = destinationType.GetProperty(destinationPropertyName);
if (destinationProperty.PropertyType == sourceProperty.PropertyType)
{
destinationProperty.SetValue(destination, sourceProperty.GetValue(source, null), null);
}
else
{
Type d1 = typeof(MapClass<,>);
Type[] typeArgs = { destinationProperty.GetType(), sourceType.GetType() };
Type constructed = d1.MakeGenericType(typeArgs);
object o = Activator.CreateInstance(constructed, null);
MethodInfo theMethod = d1.GetMethod("Test");
string toto = (string)theMethod.Invoke(o,null);
}
}
}
}
private string LookupForPropertyInDestinationType(string sourcePropertyName, Type destinationType)
{
foreach (PropertyInfo property in destinationType.GetProperties())
{
if (property.Name == sourcePropertyName)
{
return sourcePropertyName;
}
}
return null;
}
}
@usr「調用泛型類的方法」與「調用類的泛型方法」不同,這裏的答案不能解決這裏的問題。 – 2017-11-16 03:28:02
@MasonZhang重新開放。 – usr 2017-11-18 22:11:23