c# - 调用泛型类的方法

标签 c# .net asp.net-mvc generics reflection

这是上下文:

我尝试编写一个映射器以将我的 DomainModel 对象动态转换为 ViewModel 对象。我遇到的问题是,当我尝试通过反射调用泛型类的方法时出现此错误:

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

谁能帮我找出问题出在哪里?不胜感激

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

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;
    }
}

最佳答案

您需要在构造类型 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);

// ...

关于c# - 调用泛型类的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3843042/

相关文章:

c# - 使用 newtonsoft 解析 JSON

.net - SQL Server 2008 层次结构数据类型的 NHibernate 映射

c# - 为 MVC 应用程序模拟 System.Web.Routing 中的 RouteData 类

asp.net - ASP.NET v4无扩展URL功能在IIS 6.0上不起作用

asp.net-mvc - 没有必需属性的bool属性是必需的

c# - 从对象中获取自定义属性

c# - 如何将 EntityReference(例如)写入 XmlWriter,由 XmlNodeReader 读取?

c# - 如何从 Windows 服务访问 WCF RIA 服务?

c# - "object is enumerated"在 C# 中是什么意思?

.net - 如何以编程方式启动 visual studio 并将其发送到特定文件/行?