Csharp/C#教程:调用generics类的方法分享


调用generics类的方法

这是上下文:

我尝试编写一个映射器来动态地将我的DomainModel对象转换为ViewModel Ojects。 我得到的问题是,当我尝试通过reflection调用generics类的方法时,我得到了这个错误:

System.InvalidOperationException:无法对ContainsGenericParameters为true的类型或方法执行后期绑定操作。

有人可以帮助我找出错误在哪里吗? 这将不胜感激

这是代码(我试图简化它):

public class MapClass { 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; } } 

您需要在构造的构造类型上调用GetMethod而不是在类型定义d1上调用。

上述就是C#学习教程:调用generics类的方法分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

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

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/959102.html

(0)
上一篇 2021年11月23日
下一篇 2021年11月23日

精彩推荐