[英]Retrieving static property value with InvokeMember
以下代碼失敗:
未處理的異常:System.MissingMethodException:找不到方法'TestApp.Example.Value'。
我還嘗試將BindingFlags.Static
更改為BindingFlags.Instance
並將實際實例作為第四個參數傳遞,但結果相同。 有什么辦法可以解決這個問題嗎?
using System.Reflection;
namespace TestApp {
class Program {
static void Main() {
var flags = BindingFlags.GetProperty | BindingFlags.Static | BindingFlags.Public;
var value = typeof(Example).InvokeMember("Value", flags, null, null, null);
}
}
public sealed class Example {
public static readonly string Value = "value";
}
}
Example.Value
是一個字段,而不是一個方法。 請改用:
var value = typeof(Example).GetField("Value").GetValue(null);
我想你正在尋找FieldInfo, msdn上的例子
class MyClass
{
public static String val = "test";
public static void Main()
{
FieldInfo myf = typeof(MyClass).GetField("val");
Console.WriteLine(myf.GetValue(null));
val = "hi";
Console.WriteLine(myf.GetValue(null));
}
}
這是一個字段,因此您希望使用GetField
和GetValue
與InvokeMember
的組合
var value = typeof(Example).GetField("Value", flags).GetValue(null);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.