2009-09-09 26 views

回答

9

是的,這是可以使用反射來設置只讀字段的值構造函數運行後

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

fi.SetValue(this, 1); 

編輯

已更新,以查看直接父類型。如果類型是通用的,這個解決方案可能會有問題。

+0

但是,通過此代碼,我無法獲取父字段。好的? – Custodio 2009-09-09 20:29:27

+0

@Luís,更新了代碼以查找父類型 – JaredPar 2009-09-09 20:32:05

+0

現在爲什麼我只能使用「 k__BackingField」來獲得我的字段? – Custodio 2009-09-11 19:32:25

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; 
+0

+1爲csharptest-net庫。它有一個有趣的記錄器。 – 2009-09-09 19:18:29

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" 
} 
0

像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); 

感謝所有。

+0

你確定idFromBaseType [0]是否是正確的字段?你可能應該按名稱匹配... – 2009-09-09 21:24:57

+0

對我而言,導致我的第一個元素是ID。 但我已經嘗試使用字符串獲取字段,但沒有成功。 – Custodio 2009-09-11 19:27:38

相關問題