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();
}
}
}
Aucun commentaire:
Enregistrer un commentaire