📜  C#| Type.GetDefaultMembers()方法

📅  最后修改于: 2021-05-29 15:54:12             🧑  作者: Mango

Type.GetDefaultMembers()方法用于查找为设置了DefaultMemberAttribute的当前Type定义的成员。

下面的程序说明了Type.GetDefaultMembers()方法的用法:

范例1:

// C# program to demonstrate the
// Type.GetDefaultMembers() Method
using System;
using System.Globalization;
using System.Reflection;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
        // Declaring and initializing obj
        object obj = "Ram";
  
        // Getting the type of obj
        // using GetType() Method
        Type type = obj.GetType();
  
        // Getting the DefaultMembers
        // using GetDefaultMembers() Method
        MemberInfo[] info = type.GetDefaultMembers();
  
        // Display the result
        for (int i = 0; i < info.Length; i++)
  
            Console.WriteLine("Result is:  {0}", info[i]);
    }
}
输出:
Result is:  Char Chars [Int32]

范例2:

// C# program to demonstrate the
// Type.GetDefaultMembers() Method
using System;
using System.Globalization;
using System.Reflection;
  
// Setting DefaultMemberAttribute
[DefaultMemberAttribute("name")] class GFG {
  
    // Main Method
    public static void Main()
    {
        // Declaring and initializing
        // object of Type dataType
        Type type = typeof(GFG);
  
        // Getting the DefaultMembers
        // using GetDefaultMembers() Method
        MemberInfo[] info = type.GetDefaultMembers();
  
        if (info.Length != 0)
        {
            for (int i = 0; i < info.Length; i++)
                Console.WriteLine("Result is:  {0}", info[i]);
        }
        else {
            Console.WriteLine("DefaultMember is not found");
        }
    }
  
    // Defining Member Attributes
    public void Name(String s) {}
  
    // Defining property
    public String name
    {
        // property or indexer must 
        // have at least one accessor
        get
        {
            return "Ram";
        }
    }
}
输出:
Result is:  System.String name

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.type.getdefaultmembers?view=netframework-4.8