像Java中我有:我可以使用反射更改C#中的私有隻讀繼承字段嗎?
Class.getSuperClass().getDeclaredFields()
我怎麼能知道並從超集私人領域?
我知道這是強烈不建議,但我正在測試我的應用程序,我需要模擬一個錯誤的情況,其中id是正確的,而不是名稱。但是這個ID是私人的。
像Java中我有:我可以使用反射更改C#中的私有隻讀繼承字段嗎?
Class.getSuperClass().getDeclaredFields()
我怎麼能知道並從超集私人領域?
我知道這是強烈不建議,但我正在測試我的應用程序,我需要模擬一個錯誤的情況,其中id是正確的,而不是名稱。但是這個ID是私人的。
是的,這是可以使用反射來設置只讀字段的值構造函數運行後
var fi = this.GetType()
.BaseType
.GetField("_someField", BindingFlags.Instance | BindingFlags.NonPublic);
fi.SetValue(this, 1);
編輯
已更新,以查看直接父類型。如果類型是通用的,這個解決方案可能會有問題。
這個類可以讓你做到這一點:
http://csharptest.net/browse/src/Library/Reflection/PropertyType.cs
用法:
new PropertyType(this.GetType(), "_myParentField").SetValue(this, newValue);
BTW,這將在公開/非公共字段或屬性的作用。爲了方便使用,您可以使用派生類PropertyValue這樣的:
new PropertyValue<int>(this, "_myParentField").Value = newValue;
+1爲csharptest-net庫。它有一個有趣的記錄器。 – 2009-09-09 19:18:29
是的,你可以。
有關字段,請使用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"
}
像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);
感謝所有。
你確定idFromBaseType [0]是否是正確的字段?你可能應該按名稱匹配... – 2009-09-09 21:24:57
對我而言,導致我的第一個元素是ID。 但我已經嘗試使用字符串獲取字段,但沒有成功。 – Custodio 2009-09-11 19:27:38
但是,通過此代碼,我無法獲取父字段。好的? – Custodio 2009-09-09 20:29:27
@Luís,更新了代碼以查找父類型 – JaredPar 2009-09-09 20:32:05
現在爲什麼我只能使用「 k__BackingField」來獲得我的字段? –
Custodio
2009-09-11 19:32:25