這是故意冗長,所以你會得到什麼正在發生的事情一步一步來。它檢查類型A中的所有字段並查找名爲「foo」的字段。
編輯:它也適用於A在不同的命名空間。
namespace DifferentNamespace
{
class A
{
public static string foo = "hello";
}
}
class Program {
static void Main(string[] args) {
Type type = typeof(DifferentNamespace.A);
FieldInfo[] fields = type.GetFields();
foreach (var field in fields)
{
string name = field.Name;
object temp = field.GetValue(null); // Get value
// since the field is static
// the argument is ignored
// so we can as well pass a null
if (name == "foo") // See if it is named "foo"
{
string value = temp as string;
Console.Write("string {0} = {1}", name, value);
}
Console.ReadLine();
}
}
}
是的,你可以,但要非常小心,這樣做 - 即使它是一個CLR類,它可能會在服務包改變。 – 2011-03-16 09:54:03