Rem*_*yth 14 c# reflection properties
我正在尝试使用反射从类中获取属性.以下是我所看到的一些示例代码:
using System.Reflection;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
PropertyInfo[] tmp2 = typeof(TestClass).GetProperties();
PropertyInfo test = typeof(TestClass).GetProperty(
"TestProp", BindingFlags.Public | BindingFlags.NonPublic);
}
}
public class TestClass
{
public Int32 TestProp
{
get;
set;
}
}
}
Run Code Online (Sandbox Code Playgroud)
当我追溯到这一点时,这就是我所看到的:
GetProperties(),结果数组有一个条目,用于属性TestProp.TestProp使用时GetProperty(),我得到null.我有点难过; 我无法在MSDN中找到任何关于GetProperty()向我解释此结果的内容.有帮助吗?
编辑:
如果我添加BindingFlags.Instance到GetProperties()通话中,则找不到属性,句点.这更加一致,并使我相信TestProp由于某种原因不被视为实例属性.
那为什么会这样?我需要对该属性做什么才能将此属性视为实例属性?
And*_*ngs 12
添加BindingFlags.Instance到GetProperty通话.
编辑:回应评论......
以下代码返回该属性.
注意:在尝试检索它之前实际让你的属性做某事是个好主意(VS2005):)
using System.Reflection;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
PropertyInfo[] tmp2 = typeof(TestClass).GetProperties();
PropertyInfo test = typeof(TestClass).GetProperty(
"TestProp",
BindingFlags.Instance | BindingFlags.Public |
BindingFlags.NonPublic);
Console.WriteLine(test.Name);
}
}
public class TestClass
{
public Int32 TestProp
{
get
{
return 0;
}
set
{
}
}
}
}
Run Code Online (Sandbox Code Playgroud)