C# 反射:获取类和基类的所有成员的信息 [英] C# Reflection: Get info for all members of class and base classes

查看:314
本文介绍了C# 反射:获取类和基类的所有成员的信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我运行以下代码时,它只返回一个 MethodInfo/FieldInfo/etc.直接属于我在其中搜索信息对象的 Type.我如何找到信息对象,而不管它驻留在基类中并且可能是私有的?

When I run the following code, it only returns a MethodInfo/FieldInfo/etc. that belongs directly to the Type that I'm searching for the info object in. How do I find the info object regardless of the fact that it resides in a base class and could be private?

obj.GetType().GetMethod(methodName, bindingFlags);

推荐答案

如果在子类中找不到 info 对象,以下代码将查看对象的每个基类.请注意,虽然它会返回基类信息对象,但它会返回它首先遇到的"对象,因此如果您的子类中有一个名为 _blah 的变量和一个名为 的变量>_blah ,则返回子类的 _blah .

The following code will look through each base class of an object if the info object is not found in the child class. Note that though it will return the base class info object, it will return the object that it "runs into first", so if you have a variable called _blah in your child class and a variable called _blah in a base class, then the _blah from the child class will be returned.

public static MethodInfo GetMethodInfo(this Type objType, string methodName, BindingFlags flags, bool isFirstTypeChecked = true)
{
    MethodInfo methodInfo = objType.GetMethod(methodName, flags);
    if (methodInfo == null && objType.BaseType != null)
    {
        methodInfo = objType.BaseType.GetMethodInfo(methodName, flags, false);
    }
    if (methodInfo == null && isFirstTypeChecked)
    {
        throw new MissingMethodException(String.Format("Method {0}.{1} could not be found with the following BindingFlags: {2}", objType.ReflectedType.FullName, methodName, flags.ToString()));
    }
    return methodInfo;
}

public static FieldInfo GetFieldInfo(this Type objType, string fieldName, BindingFlags flags, bool isFirstTypeChecked = true)
{
    FieldInfo fieldInfo = objType.GetField(fieldName, flags);
    if (fieldInfo == null && objType.BaseType != null)
    {
        fieldInfo = objType.BaseType.GetFieldInfo(fieldName, flags, false);
    }
    if (fieldInfo == null && isFirstTypeChecked)
    {
        throw new MissingFieldException(String.Format("Field {0}.{1} could not be found with the following BindingFlags: {2}", objType.ReflectedType.FullName, fieldName, flags.ToString()));
    }
    return fieldInfo;
}

这篇关于C# 反射:获取类和基类的所有成员的信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆