Description
[Note: This attribute is used by the System.Type.InvokeMember methods. This attribute can be applied to classes, structs, and interfaces.]
Example
using System;
using System.Reflection;
/// <summary>
/// This example shows how the DefaultMemberAttribute is used by Reflection.
/// </summary>
public class DefaultMemberAttributeSample
{
public static void Main()
{
foreach (MemberInfo m in typeof(ExampleOne).GetDefaultMembers())
{
Console.WriteLine("Default Member == {0}", m);
}
foreach (MemberInfo m in typeof(ExampleTwo).GetDefaultMembers())
{
Console.WriteLine("Default Member == {0}", m);
}
ExampleTwo exampleTwo = new ExampleTwo();
int value = (int)typeof(ExampleTwo).InvokeMember(string.Empty,
BindingFlags.InvokeMethod, null, exampleTwo, null);
Console.WriteLine("Invoke default member of ExampleTwo: {0} ",
value);
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("Press Enter to continue");
Console.ReadLine();
}
}
//The C# compiler emits the DefaultMember
//attribute for types with indexers
public class ExampleOne
{
//Sample meaningless indexer
public int this [int index]
{
get
{
return new Random().Next();
}
}
}
//We customize this example by explicitly telling the runtime
//what the default member is.
[DefaultMember("GetMeaninglessValue")]
public class ExampleTwo
{
//Sample meaningless method
public int GetMeaninglessValue()
{
return new Random().Next();
}
}
The output is
Default Member == Int32 Item [Int32]
Default Member == Int32 GetMeaninglessValue()
Invoke default member of ExampleTwo: 1342094916
Press Enter to continue
|