2016-03-01 65 views
0

我一直試圖調用隊列上的count屬性。我試過各種各樣的調用。如何從隊列計數中獲取計數的int值?使用反射從隊列中計數

語法即時試圖使用,但不工作是

(ConsoleKey)Dequeue.Invoke(InputQueue,新的對象[] {});

正確的語法是: var queueObj = InputQueue.GetMethod.Invoke(magicClassObject,new object [] {});

 public class ReflectionAttempts 
     { 
      Type magicType; 
      object magicClassObject; 
      MethodInfo UpdateView; 
      PropertyInfo InputQueue; 
      PropertyInfo Count; 
      MethodInfo Dequeue; 
      public ReflectionAttempts(Type magicType) 
      { 
       this.magicType = magicType; 
       magicClassObject = Activator.CreateInstance(magicType); 
       InputQueue = magicType.GetProperty("InputQueue"); 
       Count = InputQueue.PropertyType.GetProperty("Count"); 
       Dequeue = InputQueue.PropertyType.GetMethod("Dequeue"); 
       var queueObj = InputQueue.GetMethod.Invoke(magicClassObject, new object[] { }); 

       int theCount = (int) Count.GetMethod.Invoke(queueObj, new object[] { }); 
       Input abc = (Input) Dequeue.Invoke(queueObj, new object[] { }); 

      } 
     } 
+1

不能使用'InputQueue'作爲參數'Invoke'因爲它是一個'PropertyInfo'。您應該通過獲取其Get方法並將其調用到對象上來獲取InputQueue屬性的值。就像'var queueObj = InputQueue.GetMethod.Invoke(magicClassObject,new object [] {})',然後用'queueObj'代替:'Dequeue.Invoke(queueObj,...);' – elchido

+0

如果你回答這個問題,生病將其標記爲正確的答案。非常感謝。我不知道我正在做的事是否會起作用。有用。所以現在如果我想這樣做,我有這個選項。因爲現在我可以加載任何我想要的東西進入這個程序...:D – MakerOfTheUnicake

+0

發表回答。 – elchido

回答

1

高興它爲你工作,這裏有雲作爲一個答案:

不能使用InputQueue作爲參數Invoke,因爲它是一個PropertyInfo。您應該通過獲取其Get方法並在對象上調用它來獲取InputQueue屬性的值。像

var queueObj = InputQueue.GetMethod.Invoke(magicClassObject, new object[]{}) 

東西然後使用queueObj代替:

Dequeue.Invoke(queueObj, ...); 
0

本質上,它是:

PropertyInfo piCount = ...; 
var count = (int)piCount.GetValue(InputQueue); 

但我強烈建議重新設計這種以這樣的方式,當你不需要使用反射(如果可能)。這不是一個好的設計,很慢,很難實施和維護。

像這樣:

class GameStateMachine<T> where T : GameViewMachine 
{ 
} 

abstract class GameViewMachine 
{ 
    public int Count { get; } 
    public IQueue InputQueue { get; } 
} 
+0

我可能會重新設計它。我希望能夠連接任何類型的視圖,而不知道它想要什麼類型的輸入。這就是爲什麼我決定嘗試使用反思。讓我試試你的代碼。 – MakerOfTheUnicake

+0

我得到的錯誤:_COMPlusExceptionCode = -532462766 – MakerOfTheUnicake

+0

但現在我必須在某處指定機器的類型。如果我剛剛通過反射獲得隊列工作。我不必。 – MakerOfTheUnicake