2010-11-04 64 views
3

得到一個私有成員變量,我有以下結構:C#中使用反射來從派生

abstract class Parent {} 


class Child : Parent 
{ 
    // Member Variable that I want access to: 
    OleDbCommand[] _commandCollection; 

    // Auto-generated code here 
} 

是否有可能使用反射從父類中的子類中訪問_commandCollection?如果沒有關於我如何實現這一目標的建議?

編輯: 它可能值得一提的是,在父類的抽象我打算使用IDbCommand的[]來處理_commandCollection對象不是我一個人的TableAdapter將使用的OleDb連接到各自的數據庫。

EDIT2: 對於所有評論說...只是功能的屬性添加到子類,我不能作爲其自動由VS設計器生成。我真的不希望每次改變設計師的東西時都不得不重新開始工作!

+5

哇。這是一個很大的代碼味道。爲什麼不把'_commandCollection'放在父類中,並將其輸入爲'IDbCommand []'?那麼你有你想要的東西,你只是在兒童班上投了。 – 2010-11-04 14:37:49

+0

@TK我建議你看看你的代碼架構。如果缺少控制器類,則會發生這種情況。 – honibis 2010-11-04 15:03:23

+0

傳統知識 - 我可以涉及到你的問題。 MS有習慣在生成的代碼中設置私有的東西,這些代碼確實需要從派生類訪問。我將用它來做類似的事情。 – shindigo 2012-02-10 20:07:27

回答

9
// _commandCollection is an instance, private member 
BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic; 

// Retrieve a FieldInfo instance corresponding to the field 
FieldInfo field = GetType().GetField("_commandCollection", flags); 

// Retrieve the value of the field, and cast as necessary 
IDbCommand[] cc =(IDbCommand[])field.GetValue(this); 

數組協方差應確保演員成功。

我假設一些設計師將生成子類?否則,一個受保護的財產可能是你正在尋找的。

1

這是可能的,但它是一個絕對不好的主意。

var field = GetType().GetField("_commandCollection", BindingFlags.Instance | BindingFlags.NonPublic); 

我覺得你真的想要做的是提供一種方法爲子綱,以提供家長與所需的數據:

protected abstract IEnumerable<IDBCommand> GetCommands(); 
+0

我意識到,在大多數情況下,私人真的意味着'雙手不要碰',但在這種情況下,我試圖讓一個單一的解決方案,讓我所有(100 +)表適配器使用這個通用的代碼片段比創建和維護100多個部分課程。 – 2010-11-04 14:39:44