如何从泛型类的方法调用类 T 的非泛型方法?

问题描述

我是反射和依赖注入概念的新手,为了更好地理解,我开始运行一些代码

我试图从包含 T 对象的泛型类的方法调用类 T 的非泛型方法

考虑以下示例代码,当我运行它时,我得到:

system.invalidOperationException: Void displayproperty() 不是 通用方法定义。 MakeGenericmethod 只能在 MethodBase.IsGenericmethodDeFinition 为 true 的方法

我做错了什么?

using System;
using System.Collections.Generic;
using System.Reflection;
namespace di001
{
    class MyDependency
    {
        private String _property;
        public String Property
        {
           get => _property;
           set => _property = value;
        }
        public void displayproperty()
        {
            Console.WriteLine(Property);
        }
    }

    class DIClass<T>
    {
        public T obj;
        public void displayMessage()
        { 
             MethodInfo method = typeof(T).getmethod("displayProperty");
             MethodInfo generic = method.MakeGenericmethod(typeof(T));
             generic.Invoke(this,null);
        }
        public DIClass(T obj)
        {
            this.obj = obj;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            DIClass<MyDependency> x = new DIClass<MyDependency>(new MyDependency());
            x.displayMessage();
        }
    }
}

解决方法

线

MethodInfo generic = method.MakeGenericMethod(typeof(T));

完全没有必要。

此时,在实际执行时,T 不是泛型的,因为它已被构造(T 是您想要的实际类型)。 method 无论如何肯定不是通用方法。

你应该能够做到

typeof(T).GetMethod("DisplayProperty").Invoke(...

我还假设您想使用参数 Invoke

调用 (obj,null)