Type.GetDefaultMembers()方法用于查找为设置了DefaultMemberAttribute的当前Type定义的成员。
Syntax: public virtual System.Reflection.MemberInfo[] GetDefaultMembers ();
Return Value: This method returns an array of MemberInfo objects representing all default members of the current Type or an empty array of type MemberInfo, if the current Type does not have default members.
下面的程序说明了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