2016-07-13 11 views
0

クラス内のオブジェクトのプロパティを設定しようとしていますが、エラーはObject does not match target typeと表示されます。C#Reflection - プロパティ値を設定

FieldInfo dControl = window.GetType().GetField("dControl", BindingFlags.NonPublic | BindingFlags.Instance); 
if (dControl == null) { Debug.Log ("dControl is null"); return;} 

Type typeDC = dControl.FieldType; 
PropertyInfo inPreviewMode = typeDC.GetProperty("InPreviewMode", BindingFlags.Public | BindingFlags.Instance); 
if (inPreviewMode == null) { Debug.Log ("dControl.InPreviewMode is null"); return;} 

bool value = false; 
inPreviewMode.SetValue(dControl, value, null); 

これは、私がアクセスしようとしているプロパティです:

public class DControl : TimeArea 
{ 
    public bool InPreviewMode 
    { 
     get 
     { 
      return dState.IsInPreviewMode; 
     } 
     set 
     { 
      if (cutscene != null) 
      { 
       ... 
      } 
     } 
     dState.IsInPreviewMode = value; 
    } 
    ... 
} 

ヘルプが理解されます。

+3

はなぜ 'dState.IsInPreviewMode =値が設定値にそれを渡す:

だから、リフレクション経由でそのインスタンスを取得する必要がある場合があります'? –

+0

フィールドは常に 'DControl'のインスタンスになると思いますか?あなたはフィールド値を取得してキャストすることができます。代わりに 'inPreviewMode.SetValue(dControl.GetValue(window)、value、null)'のようなことをする必要があります。 – Lee

答えて

2

SetValueの最初のパラメータは、値を設定するインスタンスです。つまり、のインスタンスがあると想定しています。コードには、FieldInfoのインスタンスが渡されます。 ; ``セット外

DControl ctrl = (DControl)dControl.GetValue(window); 

をそして

inPreviewMode.SetValue(ctrl, value, null); 
関連する問題