为什么我的C#反射代码崩溃了?

pro*_*ice 1 c#

我只想反思:

using System;
using System.Collections.Generic;
using System.Reflection;


public class CTest {
    public string test;
}

public class MyClass
{
    public static void Main()
    {
        CTest cTest = new CTest();
        Type t=cTest.GetType();
        PropertyInfo p = t.GetProperty("test");
        cTest.test = "hello";
        //instruction below makes crash
        string test = (string)p.GetValue(cTest,null);

        Console.WriteLine(cTest.GetType().FullName);
        Console.ReadLine(); 
    }
}
Run Code Online (Sandbox Code Playgroud)

Meh*_*ari 11

" test"不是财产,而是一个领域.您应该使用Type.GetField方法来获得FieldInfo:

CTest CTest = new CTest();
Type t = CTest.GetType();
FieldInfo p = t.GetField("test");
CTest.test = "hello";
string test = (string)p.GetValue(CTest);

Console.WriteLine(CTest.GetType().FullName);
Console.ReadLine();     
Run Code Online (Sandbox Code Playgroud)


Mar*_*ell 8

其他人观察到该成员是一个领域.IMO,不过,最好的解决办法是一个属性.除非你正在做一些非常具体的事情,否则触摸领域(来自课外)往往是一个坏主意:

public class CTest {
    public string test { get; set; }
}
Run Code Online (Sandbox Code Playgroud)