当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C# Type.GetDefaultMembers()用法及代码示例


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

用法: public virtual System.Reflection.MemberInfo[] GetDefaultMembers ();

返回值:如果当前Type没有默认成员,则此方法返回代表当前Type的所有默认成员的MemberInfo对象的数组,或者返回MemberInfo类型的空数组。


以下示例程序旨在说明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

参考:



相关用法


注:本文由纯净天空筛选整理自RohitPrasad3大神的英文原创作品 C# | Type.GetDefaultMembers() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。