Reputation: 75
I'm running into some odd behavior with reflection. It seems like a bug. I've been using reflection in my c# project to access public fields in my various custom data types. I've been using mono to run my code on a Mac but for the first time, I built a native stand-alone project using "dotnet publish -r osx-x64 -c Release --self-contained -p:PublishAot=true". Everything works correctly except GetField/GetFields.
A class in my project has a public string called name, for example. Let's say that class is called being.
//o is of type object which is an instance of being
o.GetType().GetField("name").SetValue(o, "somevalue");
The line above crashes with an object reference not set to an instance of an object because GetField("name") returns null. Similarly, GetFields() returns an empty array even though I have dozens of public fields in being.
The reason this seems like a bug to me is, it will work if I access being in this manner first:
var field = typeof(being).GetField("name");
I don't even have to DO anything with field. Simply calling GetField() on typeof(being) will make the GetType() from my instance suddenly start returning fields. HUH? How is this possible since the line above is not even involved? I need a workaround regardless of whether it's a bug or not. In some cases, I don't know the type at compile time so I can't do typeof(being), typeof(monster), etc. I have to rely on GetType().
Thanks in advance!
Upvotes: 0
Views: 45