I am currently learning C# Generics and reflection. I want to call a method "toString" of a generic class T. The problem is that my program crashes with a null point exception - "nameMethod" variable below is null and I cannot figure out why "t.GetMethod("toString");" call below returns null. This is my code:
public class ViewModel<T> where T: EntityBase
{
public ViewModel()
{
T _model = Activator.CreateInstance<T>();
Type t = typeof(T);
MethodInfo nameMethod = t.GetMethod("ToString");
Console.WriteLine(nameMethod.Invoke(_model, null));
}
}
BasePlant class:
public class BasePlant : EntityBase
{
public string GetName => "TESTING NAME METHOD";
public override string ToString()
{
return GetName;
}
}
Usage:
static void Main(string[] args)
{
var vm = new ViewModel<BasePlant>();
Console.ReadKey();
}
I am stuck at this crash and I am not sure what I am doing wrong. I would appreciate any help.
Aucun commentaire:
Enregistrer un commentaire