Почему мой код отражения 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 ответа
Решение
"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();
Другие заметили, что участник является полем. ИМО, тем не менее, лучшее решение - сделать его собственностью. Если вы не делаете какие-то очень специфические вещи, трогать поля (вне класса) обычно плохая идея:
public class CTest {
public string test { get; set; }
}
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();
}
}