2013-03-29 14 views
1

當我運行以下代碼時,它只返回一個MethodInfo/FieldInfo/etc。直接屬於Type,我正在尋找info對象。我如何找到info對象,而不管它駐留在基類中,並且可能是私有的?
C#思考:獲取類和基類的所有成員的信息

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

回答

1

下面的代碼將查看每基類對象的,如果info對象並不在子類中找到。請注意,雖然它將返回基類信息對象,但它將返回它「首先運行」的對象,因此如果您的子類中有一個名爲_blah的變量,並且在基類中有一個名爲_blah的變量,那麼_blah從小孩班將退回。

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; 
} 
3

嗯,你回答了你自己的問題,但據我瞭解,你主要的要求是How do I find the info object regardless of where it is found in the hierarchy?

你不需要遞歸這裏得到所有成員的完整的層次。您可以在Type上使用GetMembers函數,它將返回包括所有基類的所有成員。

接下來的代碼示例說明了這一點:

var names = 
    typeof(MyClass).GetMembers() 
        .Select (x => x.Name); 

Console.WriteLine (string.Join(Environment.NewLine, names)); 

這種結構

class MyClass : Base 
{ 
    public string Name { get; set; } 
    public string Surname { get; set; } 
} 

class Base 
{ 
    public string Name { get; set; } 
} 

回報

get_Name 
set_Name 
get_Surname 
set_Surname 
get_Name 
set_Name 
ToString 
Equals 
GetHashCode 
GetType 
.ctor 
Name 
Surname 

注意get_Name訪問器自動屬性,因爲MyClass隱藏Name財產出現了兩次b Ase類。另外請注意ToString,GetType和其他方法,定義在object

+0

我已經更新了我的問題,以更具體到我想發佈的內容。非常感謝您的回答,非常豐富。 – bsara

+1

我只想提到,如果基類是抽象的,那麼你需要使用BindingFlags.FlattenHierarchy。請參閱此處的示例:http://stackoverflow.com/questions/5675006/how-to-get-public-static-method-of-base-class – RenniePet