我有这段代码用于根据属性的字符串名称获取属性的值
public class Person
{
public String LastName;
}
static void Main()
{
Person person1 = new Person { Born = new DateTime(1989, 10, 7), FirstName = "John", LastName = "Smith" };
string propertytoGet = "LastName";
object wantedProperty = person1.GetType().GetProperty(propertytoGet).GetValue(person1, null);
}
我得到空引用异常,因为GetProperty(propertytoGet)
返回空。我在stackoverflow上找到了这个解决方案,它被标记为答案,但它对我不起作用。