简体   繁体   中英

What's the difference between DeclaredMembers from TypeInfo and GetMembers from Type?

below is some source code:

public abstract class Type : MemberInfo, _Type, IReflect {
   public MemberInfo[] GetMembers();
   public MethodInfo[] GetMethods();
   public FieldInfo[] GetFields();
   public PropertyInfo[] GetProperties();
   public ConstructorInfo[] GetConstructors();
   ...
}

public abstract class TypeInfo : Type, IReflectableType {
   public virtual IEnumerable<MemberInfo> DeclaredMembers { get; }
   public virtual IEnumerable<MethodInfo> DeclaredMethods { get; }
   public virtual IEnumerable<FieldInfo> DeclaredFields { get; }
   public virtual IEnumerable<PropertyInfo> DeclaredProperties { get; }
   public virtual IEnumerable<ConstructorInfo> DeclaredConstructors { get; }
   ...
}

My question is, what's the difference betweet using GetXXX in Type and its counterpart DeclaredXXX in TypeInfo? They looks identical, and if you already have a batch in Type , why we still another batch in TypeInfo considering TypeInfo inherits from Type ?

According to the DeclaredOnly BindingFlags used in the source it seems only members that are "declared at the level of the supplied type's hierarchy" are considered. So inherited members are not considered.

This proves that it's true:

void Main()
{
    TypeInfo fooType = typeof(Foo).GetTypeInfo();
    Console.WriteLine("Declared properties");
    foreach(var m in fooType.DeclaredProperties)
    {
        Console.WriteLine(m.Name);
    }
    
    Console.WriteLine();
    Console.WriteLine("Properties");
    foreach (var m in fooType.GetProperties())
    {
        Console.WriteLine(m.Name);
    }
}

public class Foo: Bah
{
    public string Name{get;set;}
}
public class Bah
{
    public int Id{get;set;} 
}

This prints:

Declared properties
Name

Properties
Name
Id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM