What does System.Reflection.TargetException: Non-static method requires a target. mean?
Asked Answered
T

2

11

In my application I receive the functionCode value from somewhere and need to reflect the appropriate class. I tried to reflect the appropriate type According to this solution. but it doesn't work for me. I can not use GetField() method because I'm working on a PCL project. Therefore I tried these lines of code:

AssemblyName name = new AssemblyName("MyLibrary");
var type = Assembly.Load(name);
type.DefinedTypes.FirstOrDefault(x =>
x.GetDeclaredProperty("functionCode") != null &&
 (byte)x.GetDeclaredProperty("functionCode").GetValue(null) == val);

It does not work too. It throws System.Reflection.TargetException: Non-static method requires a target.

Tocantins answered 5/2, 2015 at 10:59 Comment(1)
Possibly related: https://mcmap.net/q/809574/-non-static-method-requires-a-target-cCapsize
S
16

It means non static method requires an object. If you have an instance member then you have to use an instance to get it's value. Because without an instance it doesn't exist.So you need to pass an instance of the type instead of null to GetValue method.Or make the member static if you don't want it to be an instance member.

Sailesh answered 5/2, 2015 at 11:1 Comment(3)
Thank you. I wrote this and it works: DefinedTypes.FirstOrDefault(x => x.GetDeclaredProperty("functionCode") != null && !x.IsAbstract && x.BaseType == typeof(MyClass) && (byte)x.GetDeclaredProperty("functionCode").GetValue(Activator.CreateInstance(x.AsType()), null) == val); Is that Ok? I'd be appreciated if you guide me to a better solution. ThanksTocantins
@Tocantins it is okey if the value of property doesn't change for different instances. and btw, if that is the case I would make it static rather than an instance memberIndeclinable
Thanks. I can not make it static it should be inheritable.Tocantins
C
3

Another reason for this error is that when you read a value from an instance object and the instance object you read from is null.

Centerboard answered 9/4, 2023 at 8:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.