我认为你的Id属性有private
或protected
修饰符。然后,你必须使用GetProperty
方法的第一个重载:
using System;
using System.Reflection;
class Program
{
static void Main()
{
Test t = new Test();
Console.WriteLine(t.GetType().GetProperty("Id1").GetValue(t, null));
Console.WriteLine(t.GetType().GetProperty("Id2").GetValue(t, null));
Console.WriteLine(t.GetType().GetProperty("Id3").GetValue(t, null));
//the next line will throw a NullReferenceExcption
Console.WriteLine(t.GetType().GetProperty("Id4").GetValue(t, null));
//this line will work
Console.WriteLine(t.GetType().GetProperty("Id4",BindingFlags.Instance | BindingFlags.NonPublic).GetValue(t, null));
//the next line will throw a NullReferenceException
Console.WriteLine(t.GetType().GetProperty("Id5").GetValue(t, null));
//this line will work
Console.WriteLine(t.GetType().GetProperty("Id5", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(t, null));
}
public class Test
{
public Test()
{
Id1 = 1;
Id2 = 2;
Id3 = 3;
Id4 = 4;
Id5 = 5;
}
public int Id1 { get; set; }
public int Id2 { private get; set; }
public int Id3 { get; private set; }
protected int Id4 { get; set; }
private int Id5 { get; set; }
}
}
如果你有public
属性,你可以使用新的dynamic
关键字:
static void Main()
{
dynamic s = new Test();
Console.WriteLine(s.Id1);
Console.WriteLine(s.Id3);
}
注意Id2, Id4 and Id5
不会与dynamic
工作关键字,因为他们没有公共代理。
我认为null是指未能检索到名称为“id”的财产。你的代码中该属性的外观如何? – Tigran
请告诉我们什么类型是'userData'和它的结构。 –