reflection得到FieldInfo对象的类型?

全部,我需要访问声明的类SomeClass在Wrapper类中有一个私有字段,使用Reflection到目前为止我已经能够获得私有字段成员。 如何将其转换回原始类型,以便我可以访问它的属性和其他成员。

internal class Program { private static void Main(string[] args) { Wrapper wrap = new Wrapper { SOmeProperty = new SomeClass { Number = 007 } }; Type type = wrap.GetType(); FieldInfo[] infos = type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance); foreach (var item in infos) { } } } internal class SomeClass { public int Number { get; set; } } internal class Wrapper { private SomeClass _tempSomeObj; public SomeClass SOmeProperty { get { return _tempSomeObj; } set { _tempSomeObj = value; } } } 

我不知道我是否理解这个问题是正确的。 你想要私有字段的类型(支持字段)?

然后你可以检查FieldInfo的FieldType属性….

像这样:

 internal class Program { #region Methods private static void Main(string[] args) { var wrap = new Wrapper { SOmeProperty = new SomeClass { Number = 007 } }; Type type = wrap.GetType(); FieldInfo[] fieldInfos = type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance); foreach (var fieldInfo in fieldInfos) { if (fieldInfo.FieldType == typeof(SomeClass)) { Console.WriteLine("Yap!"); } } } #endregion } internal class SomeClass { #region Properties public int Number { get; set; } #endregion } internal class Wrapper { #region Properties public SomeClass SOmeProperty { get; set; } #endregion } 

改为使用PropertyInfo

 internal class Program { private static void Main(string[] args) { Wrapper wrap = new Wrapper { SOmeProperty = new SomeClass { Number = 007 } }; Type type = wrap.GetType(); PropertyInfo info = type.GetProperty("SOmeProperty", BindingFlags.NonPublic | BindingFlags.Instance); SomeClass value = (SomeClass)info.GetValue(wrap, null); // use `value` variable here } } 

关于你想要做什么,我仍然有点模糊,但你总是可以在任何对象上获取GetType()并得到它的实际运行时类型,并查询其他类型的属性字段,例如

 public void ListPropertiesOfType( object targetObject, Type propertyType ) { foreach( var foundProperty in targetObject.GetType( ).GetProperties( ).Where( p => p.PropertyType == propertyType ) ) { Console.WriteLine( "Name: {0}, Value: {1}", foundProperty.Name, foundProperty.GetValue( targetObject, null ) ); } } ListPropertiesOfType(new Wrapper(), typeof(SomeClass)) ListPropertiesOfType(new Wrapper(), typeof(SomeOtherClass)) 

如果你想传入Someclass和SomeClass的实例也很好,只需在实例上使用GetType()来获取你可以用来查找该类型属性的类型,如上所示。 无论你是如何使方法通用并传入“T”,或者如果它是非generics的并传入“对象”,这都是一样的