Fab*_*ano 27 .net c# reflection
有了Type.GetProperties()你可以检索你的当前类的所有属性和public基类的属性.是否有可能获得private基类的属性?
谢谢
class Base
{
private string Foo { get; set; }
}
class Sub : Base
{
private string Bar { get; set; }
}
Sub s = new Sub();
PropertyInfo[] pinfos = s.GetType().GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
foreach (PropertyInfo p in pinfos)
{
Console.WriteLine(p.Name);
}
Console.ReadKey();
Run Code Online (Sandbox Code Playgroud)
这只会打印"Bar",因为"Foo"属于基类和私有.
Mar*_*ell 47
获取给定的所有属性(public + private/protected/internal,static + instance)Type someType(可能使用GetType()获取someType):
PropertyInfo[] props = someType.BaseType.GetProperties(
BindingFlags.NonPublic | BindingFlags.Public
| BindingFlags.Instance | BindingFlags.Static)
Run Code Online (Sandbox Code Playgroud)
迭代基本类型 (type = type.BaseType),直到 type.BaseType 为 null。
MethodInfo mI = null;
Type baseType = someObject.GetType();
while (mI == null)
{
mI = baseType.GetMethod("SomePrivateMethod", BindingFlags.NonPublic | BindingFlags.Instance);
baseType = baseType.BaseType;
if (baseType == null) break;
}
mI.Invoke(someObject, new object[] {});
Run Code Online (Sandbox Code Playgroud)