문제

Java에서와 마찬가지로 나는 다음과 같습니다.

Class.getSuperClass().getDeclaredFields()

슈퍼 클래스에서 개인 필드를 알고 설정하는 방법은 무엇입니까?

나는 이것이 권장되지 않는다는 것을 알고 있지만 응용 프로그램을 테스트하고 있으며 ID가 올바른 경우 잘못된 상황을 시뮬레이션해야합니다. 그러나이 ID는 비공개입니다.

도움이 되었습니까?

해결책

예, 생성자가 실행 된 후 Readonly Field의 값을 설정하기 위해 반사를 사용할 수 있습니다.

var fi = this.GetType()
             .BaseType
             .GetField("_someField", BindingFlags.Instance | BindingFlags.NonPublic);

fi.SetValue(this, 1);

편집하다

직접 상위 유형을 살펴 보도록 업데이트되었습니다. 이 솔루션은 유형이 일반적인 경우 문제가있을 수 있습니다.

다른 팁

그래 넌 할수있어.

필드의 경우 사용하십시오 FieldInfo 수업. 그만큼 BindingFlags.NonPublic 매개 변수를 사용하면 개인 필드를 볼 수 있습니다.

public class Base
{
    private string _id = "hi";

    public string Id { get { return _id; } }
}

public class Derived : Base
{
    public void changeParentVariable()
    {
        FieldInfo fld = typeof(Base).GetField("_id", BindingFlags.Instance | BindingFlags.NonPublic);
        fld.SetValue(this, "sup");
    }
}

그리고 그것이 효과가 있다는 것을 증명하기위한 작은 테스트 :

public static void Run()
{
    var derived = new Derived();
    Console.WriteLine(derived.Id); // prints "hi"
    derived.changeParentVariable();
    Console.WriteLine(derived.Id); // prints "sup"
}

이 수업은 다음을 수행 할 수 있습니다.

http://csharptest.net/browse/src/library/reflection/propertype.cs

용법:

new PropertyType(this.GetType(), "_myParentField").SetValue(this, newValue);

BTW는 공공/비공개 필드 또는 속성에서 작동합니다. 사용 편의성을 위해 파생 클래스를 사용할 수 있습니다. 재산 가치 이와 같이:

new PropertyValue<int>(this,  "_myParentField").Value = newValue;

Jaredpar가 제안한 것처럼 다음을 수행했습니다.

//to discover the object type
Type groupType = _group.GetType();
//to discover the parent object type
Type bType = groupType.BaseType;
//now I get all field to make sure that I can retrieve the field.
FieldInfo[] idFromBaseType = bType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);

//And finally I set the values. (for me, the ID is the first element)
idFromBaseType[0].SetValue(_group, 1);

모두에게 감사합니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top