Created
April 12, 2014 09:09
-
-
Save lmatt-bit/10526070 to your computer and use it in GitHub Desktop.
Get or set value for a field with reflection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class RTest | |
| { | |
| public static int staticInt; | |
| public int instantInt; | |
| } | |
| Type type = typeof(RTest); | |
| var field = type.GetField("staticInt"); | |
| field.SetValue(null, 10); | |
| Console.WirteLine(field.GetValue(null));//why use null here? because this is a static field | |
| var obj = new RTest(); | |
| var field2 = type.GetField("instantInt"); | |
| field2.SetValue(obj, 11); | |
| Console.WirteLine(field.GetValue(obj));//pay attention to the parameter. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment