I have a static class
with static private readonly
member that's set via the class's static constructor
. Below is a simplified example.
public static class MyClass { private static readonly string m_myField; static MyClass() { // logic to determine and set m_myField; } public static string MyField { get { // More logic to validate m_myField and then return it. } } }
Since the above class is a static class, I cannot create an instance of it in order to utilize pass such into a FieldInfo.GetValue()
call to retrieve and later set the value of m_myField
. Is there a way I'm not aware to either get use the FieldInfo class to get and set the value on a static class or is the only option is to refactor the class I've been asked to unit test for?
Creating a static class is therefore basically the same as creating a class that contains only static members and a private constructor. A private constructor prevents the class from being instantiated.
So: field. set(null, p_fieldValue); This will let you set the static field.
A variable declared private static could easily be accessed, but only from the inside of the class in which it is defined and declared. It is because the variable is declared private, and private variables are not accessible outside the class. Within the class, they can be accessed using ClassName.
A private variable is only accessible inside the class. A static variable belongs to the class rather than to an instance of a class. Notice that the variable DEPARTMENT is also final , which means that it cannot be modified once it is set.
Here is a quick example showing how to do it:
using System; using System.Reflection; class Example { static void Main() { var field = typeof(Foo).GetField("bar", BindingFlags.Static | BindingFlags.NonPublic); // Normally the first argument to "SetValue" is the instance // of the type but since we are mutating a static field we pass "null" field.SetValue(null, "baz"); } } static class Foo { static readonly String bar = "bar"; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With