lundi 18 septembre 2023

How to invoke a static abstract method by reflection? [duplicate]

I'm trying to invoke a static abstract method by reflection. Declaring static abstract methods on interfaces is a preview feature about which you can read more here.

When invoking a non-static abstract method one can simply call TheType.GetMethod("MethodName").Invoke(null, null) and the method is invoked, but when declaring a static abstract method in a inherited interface, it doesn't seem to become a public static method in the inheriting type. An example:

I have an interface Entity declaring a static abstract method GetTableName():


public interface Entity
{
    public static abstract string GetTableName();
}

Then there are multiple types of Entities that inherit from the Entity interface and implement the GetTableName method:


static string Entity.GetTableName() => "[dbo].[SomeTable]";

When trying to add the public keyword to this implementation, an error message is given: The modifier 'public' is not valid for explicit interface implementation, which I interpret as: the interface has already declared this method as public, so remove this keyword. (Is this correct?)

When trying to invoke the static abstract method with reflection on the implementing type, the method is not found and GetMethod() returns null. During debugging, I can see that the method is declared as the full qualifier of the Entity type, followed by the method name 'GetTableName', so I have tried to invoke in multiple ways such as:


var tableName = someType.GetMethod("GetTableName").Invoke(null, null);
var tableName = someType.GetMethod("FullQualifier.Entity.GetTableName").Invoke(null, null);
var tableName = someType.GetMethod("GetTableName", BindingFlags.NonPublic).Invoke(null, null);
var tableName = someType.GetMethod("GetTableName", BindingFlags.Static).Invoke(null, null);

Sadly, all return null. Upon further debugging, the method seems to be declared as NonPublic. Still, using the NonPublic binding flag has no effect. How can one invoke the static abstract method with reflection? Any help would be much appreciated.





Aucun commentaire:

Enregistrer un commentaire