【问题标题】:How to call a non-generic method of a class T from a method of a generic class?如何从泛型类的方法中调用类 T 的非泛型方法?
【发布时间】:2021-06-06 20:52:34
【问题描述】:

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

我正在尝试从包含 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();
        }
    }
}

【问题讨论】:

  • 我认为这里的“MakeGenericMethod”有问题。
  • 我认为这行根本没有必要,T 一旦构造就不是通用的,method 肯定不是。你应该可以做typeof(T).GetMethod("DisplayProperty").Invoke 我也想你想用参数Invoke 调用(obj, null)
  • 你能试试 public void DisplayMessage(){} 如果这可行,请告诉我,我会回答这个问题
  • @Charlieface 谢谢,问题现在解决了!
  • 当您获得typeof(T) 时,将获得您实例化DIClass 的泛型类型,在本例中为MyDependency。此时您有一个完整的类定义,无需调用MakeGenericType。只需致电GetMethod("DisplayProperty") 以获取MethodInfo 然后Invoke 它。但是,DisplayPropertyMyDependency 的实例属性,因此您需要该类型的实例

标签: c# asp.net-core reflection system.reflection


【解决方案1】:

线

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

完全没有必要。

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

你应该可以做到

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

我还想象你想用参数(obj, null) 调用Invoke

【讨论】:

  • 如果方法不存在,您可能希望在调用 Invoke 时使用 null 条件 运算符 (?.):@ 987654330@
  • @Flydog57 这取决于你是希望它抛出还是忽略,我将把它留给 OP 练习
猜你喜欢
  • 2021-02-16
  • 2015-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多