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.

Consider the following sample code, when I run it I get this:

System.InvalidOperationException: Void DisplayProperty() is not a GenericMethodDefinition. MakeGenericMethod may only be called on a method for which MethodBase.IsGenericMethodDefinition is 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();
        }
    }
}

Upvotes: 0

Views: 560

Answers (1)

Charlieface
Charlieface

Reputation: 72153

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). method certainly isn't a generic method anyway.

You should be able to just do

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

I also imagine you want to call Invoke with parameters (obj, null)

Upvotes: 1

Related Questions