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

时间:2009-08-08 08:28:40

标签: 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(); 
    }
}

3 个答案:

答案 0 :(得分: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();     

答案 1 :(得分:8)

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

public class CTest {
    public string test { get; set; }
}

答案 2 :(得分:4)

test不是属性,它是成员变量。

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


public class CTest {
    public string test;
    public string test2 {get; set;}
}

public class MyClass
{
    public static void Main()
    {
        CTest CTest = new CTest();
        Type t=CTest.GetType();
        FieldInfo fieldTest = t.GetField("test");
        CTest.test = "hello";
        string test = (string)fieldTest.GetValue(CTest);
        Console.WriteLine(test);


        PropertyInfo p = t.GetProperty("test2");
        CTest.test2 = "hello2";
        //instruction below makes crash
        string test2 = (string)p.GetValue(CTest,null);
        Console.WriteLine(test2);

        Console.ReadLine();     
    }
}