나는 static class
과 static private readonly
회원을 가지고 있는데, 이는 클래스 static constructor
을 통해 설정됩니다. 아래는 간단한 예입니다. 상기 클래스는 정적 클래스이므로리플렉션을 사용하여 정적 클래스의 정적 정적 멤버를 설정할 수 있습니까?
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.
}
}
}
, I는 검색 할 FieldInfo.GetValue()
통화로 그러한 패스를 이용하기 위해 그것의 인스턴스를 생성하고 나중에 m_myField
의 값을 설정할 수 없다. FieldInfo 클래스를 사용하여 정적 클래스에 값을 설정하거나 유일한 옵션은 단위 테스트를 요청한 클래스를 리팩토링하는 것입니다.
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";
}
왜 것 : 여기 – flq
+1 그리고 그 타입이 그런 타입이라면 그 타입이 Get/SetValue 클래스의 인스턴스가 될 필요는 없습니다. 감사합니다 – JamesEggers