简体   繁体   English

如何从通用 class 的方法调用 class T 的非通用方法?

[英]How to call a non-generic method of a class T from a method of a generic class?

I am new to reflection and dependency injection concepts, and I started to run some code in order to understand better.我是反射和依赖注入概念的新手,为了更好地理解,我开始运行一些代码。

I am trying to call a non-generic method of a class T from a method of a generic class that contains a T object.我正在尝试从包含 T object 的通用 class 的方法中调用 class T 的非通用方法。

Consider the following sample code, when I run it I get this:考虑以下示例代码,当我运行它时,我得到了这个:

System.InvalidOperationException: Void DisplayProperty() is not a GenericMethodDefinition. System.InvalidOperationException:无效的 DisplayProperty() 不是 GenericMethodDefinition。 MakeGenericMethod may only be called on a method for which MethodBase.IsGenericMethodDefinition is true. MakeGenericMethod 只能在 MethodBase.IsGenericMethodDefinition 为 true 的方法上调用。

What I am doing wrong?我做错了什么?

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

The line线

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

is not necessary at all.根本没有必要。

At this point, when actually executing, T is not generic since it has been constructed ( T is the actual type you want).此时,实际执行时, T不是通用的,因为它已经被构造( T是您想要的实际类型)。 method certainly isn't a generic method anyway.无论如何, method当然不是通用方法。

You should be able to just do你应该能够做到

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

I also imagine you want to call Invoke with parameters (obj, null)我也想像你想用参数调用Invoke (obj, null)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM