dimanche 6 octobre 2019

Calling a non-static method through reflection in a static way

I have a class that declares a virtual method. However the specific implementations of this method do not explicitly refer to "this" object. They just return a value that is specific for that class.

So one might consistently desire to call this method not only on a specific object but also on the class itself. Since this is of course not possible on the syntactic level, I think it should be at least possible through reflection. That is, I want to iterate through all the classes in my assembly and determine which class returns which value as the response from the said method.

But my naive approach failed with a null reference exception when trying to invoke the method. Why? I expected it to succeeds because I have used a concrete class to identify the concrete overridden method, so the "this" object and its virtual method table is not needed to resolve the method.

How can I make it work? (of course excluding the "solution" to define a second truly static method that returns the same value).

using System;
using System.Reflection;

namespace StaticInvoke
{
    public abstract class Foo
    {
        public abstract string StaticValue {get;}
    }

    public class MyFirstFoo: Foo
    {
        public override string StaticValue {get {return "A first attempt to foo-ize Foo.";}}
    }

    class Program
    {
        public static void Main(string[] args)
        {
            Type myFirstFooType = typeof(MyFirstFoo);
            MethodInfo myFirstStaticValueMethod = myFirstFooType.GetMethod("StaticValue");
            string result = (string)myFirstStaticValueMethod.Invoke(null, null);

            Console.WriteLine("MyFirstFoo.StaticValue == "+result);

            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }
    }
}




Aucun commentaire:

Enregistrer un commentaire