我一直試圖調用隊列上的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[] { });
}
}
不能使用'InputQueue'作爲參數'Invoke'因爲它是一個'PropertyInfo'。您應該通過獲取其Get方法並將其調用到對象上來獲取InputQueue屬性的值。就像'var queueObj = InputQueue.GetMethod.Invoke(magicClassObject,new object [] {})',然後用'queueObj'代替:'Dequeue.Invoke(queueObj,...);' – elchido
如果你回答這個問題,生病將其標記爲正確的答案。非常感謝。我不知道我正在做的事是否會起作用。有用。所以現在如果我想這樣做,我有這個選項。因爲現在我可以加載任何我想要的東西進入這個程序...:D – MakerOfTheUnicake
發表回答。 – elchido