Get ctor argument used in field initializer using reflection

My assembly has several classes that have these fields:

private static Foo MyFoo = new Foo(typeof(Bar));

The argument typeof(Bar)is different for each class.

In my unit tests, I need to extract this argument dynamically.

I can find all classes and filter those that have a static field Foo. Then I have it FieldInfo.

But then I do not know how to get the type of this argument?

+4
source share
3 answers

Look. MethodBodyReaderYou can use this to look at IL and choose the type of constructor argument.

https://github.com/jbevain/mono.reflection/blob/master/Mono.Reflection/MethodBodyReader.cs

+1

FieldInfo.GetValue, static.

foreach (var foo in foos) {
  var myfoo = foo.GetFields(BindingFlags.Static).Single(fieldinfo =>  fieldinfo.FieldType == typeof(Foo));
  Foo foo = (Foo) myfoo.GetValue(null);
}

, , Foo :

public Type AType {get; set; }
public void Foo(Type t) { AType = t; }

Foo foo = (Foo) myfoo.GetValue(null);
Type fooType = foo.AType;
+1

, . , .

, , Reflection API, IL. Mono.Cecil IL.

Btw, , , . , MyFoo.SomeProperty == typeof(Bar), , Foo .

0

Source: https://habr.com/ru/post/1609245/


All Articles