开发者

GetValue on static field inside nested classes

开发者 https://www.devze.com 2022-12-26 14:00 出处:网络
I have the following class declared. I need to retreive the class structure and the static values without instanciate it.

I have the following class declared. I need to retreive the class structure and the static values without instanciate it.

public class MyClass()
{
    public static string field = "Value";

    public class nestedClass()
    {
        public static string nestedField = "NestedValue";
    }
}

I've successfuly used 开发者_运维技巧GetFields and GetNestedType to recover the class structure and GetValue(null) works fine on field, but not on nestedField. Let me sample:

var fi = typeof(MyClass).GetField("field", BindingFlags.Public | BindingFlags.Static);
var nt = typeof(MyClass).GetNestedType("nestedClass", BindingFlags.Public);
var nfi = nt.GetField("nestedField", BindingFlags.Public | BindingFlags.Static);
// All the above references are detected correctly
var value = fi.GetValue(null); // until here everything works fine. value == "Value"
var nestedValue = nfi.GetValue(null); // this one does not work!! 

Anyone knows why the last line does not work and how to work around? Thanks.


Well it all seems to work fine to me and after the last line I get the "NestedValue" string. Tried on .net frameworks 3.5 , 4 and 4.5, everything works (VS2012 Pro). ReSharper states though, that fi, and nfi might be a possible null reference.

public class MyClass() {

Don't put "()" at the end of your class, that code is still experimental, and it's redundant unless you actually want to use the experimental code, then you'd have to provide some arguments to the constructor.

0

精彩评论

暂无评论...
验证码 换一张
取 消