5

内部に2つのプライベートメンバー変数を持つクラスの単体テストを行っています。テスト中のクラスを継承するクラスを作成しました。

最初はアクセスしたい変数を作っただけprotectedでしたが、それらを非公開にしてリフレクションを使ってアクセスできたらいいなと思いました。私はグーグルでさまざまな記事を見つけました(&ここで質問されました(http://stackoverflow.com/questions/4097682/c-sharp-use-reflection-to-get-a-private-member-variable-from-a-derived -class)) 受け入れられた回答は機能しませんでした。

リンクされたSOの質問は次のように述べています:

// _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);

ただし、GetField()方法はありません。似たような方法を試してみましたGetRuntimeField()が、うまくいきませんでした。

私のコード(継承クラス内)は次のとおりです。

public List<BaseData> RealAllData
{
    get
    {
        // Use reflection to access the private variable
        FieldInfo field = GetType().GetRuntimeField("mAllData");
        return (List<BaseData>)field.GetValue(this);
    }
}

これがうまくいかない理由を誰かが知っていれば、私は感謝します。ありがとう。

4

1 に答える 1

1

リフレクション コードを、.NET 4 および Windows ストア アプリを対象とするポータブル クラス ライブラリに配置することもできます。その後、BindingFlags などを含む「古い」リフレクション API にアクセスできるようになります。

于 2012-10-24T00:30:10.650 に答える