I have a static class which looks for an implementation of an abstract type and stores it as a static property similar to the below:
public static class MyStaticClass
{
private static MyAbstractType _MyAbstractImplementation;
public static MyAbstractType MyAbstractImplementation
{
get => _MyAbstractImplementation ?? ( _MyAbstractImplementation = FindImplementation());
private set => _MyAbstractImplementation = value;
}
}
And I am trying to call a method of MyAbstractImplementation (which contains no static properties or methods) via reflection:
var myAssembly = Assembly.Load("MyStaticClassAssembly")
var myType = myAssembly.GetTypes().First(t => t.Name == "MyAbstractType");
var myImplementation = myType.GetProperties()
.First(p=>p.ReflectedType?.Name == "MyAbstractImplementation")
.GetValue(null);
var obj = myType.GetMethod("SomeMethod")?.Invoke(
null,
new object[]
{
// Some args
});
The above code causes the following exception on getting the value of MyAbstractImplementation
:
System.Reflection.TargetException: Non-static method requires a target.
Evidently, this is because I am passing null to GetValue()
, so I try passing myAssembly
rather than null and I get the following exception:
System.Reflection.TargetException: Object does not match target type.
Out of desperation, I try passing myType
and myImplementation
but I still get the same exception.
What am I meant to be passing to GetValue()
?
Aucun commentaire:
Enregistrer un commentaire