Compartilhar via


Acessando os membros padrão

Qualquer tipo pode ter um membro padrão, que é um membro que é invocado quando nenhum nome de membro é determinado. Você pode chamar membros padrão chamando o Type.InvokeMember método com String.Empty ("") como o nome do membro. InvokeMemberrecupera o System.Reflection.DefaultMemberAttribute do tipo de atributo e, em seguida, chama o proprietário. O exemplo a seguir chama o membro padrão de Class1, e o valor retornado é atribuído ao o.

Dim c As New Class1()
Dim o As Object
o = c.GetType().InvokeMember("", BindingFlags.InvokeMethod, Nothing, c, New Object(){})
Console.WriteLine("Default member result: {0}", o)
Class1 c = new Class1();
object o;
o = c.GetType().InvokeMember("", BindingFlags.InvokeMethod, null, c, new object[0]);
Console.WriteLine("Default member result: {0}", o);
Class1^ c = gcnew Class1();
Object^ o;
o = c->GetType()->InvokeMember("", BindingFlags::InvokeMethod, nullptr, c, gcnew array<Object^>(0));
Console::WriteLine("Default member result: {0}", o);

Membros padrão são indicados pela DefaultMemberAttribute atributo do tipo declarativo. A classe mostrada no exemplo a seguir tem o DefaultMemberAttribute adicionado manualmente. Não adicione o DefaultMemberAttribute manualmente se a classe tem um indexador declarado; Nesse caso, o compilador adiciona automaticamente o atributo.

<DefaultMember("GetIVal")> _
Public Class Class1
    Private ival As Integer
    Private sval As String

    Public Sub New()
        ival = 5050
        sval = "6040"
    End Sub

    Public Function GetIVal() As Integer
        Return ival
    End Function

    Public Function GetSVal() As String
        Return sval
    End Function
End Class
[DefaultMember("GetIVal")]
public class Class1
{
    private int ival;
    private string sval;

    public Class1()
    {
        ival = 5050;
        sval = "6040";
    }

    public int GetIVal()
    {
        return ival;
    }

    public string GetSVal()
    {
        return sval;
    }
}
[DefaultMember("GetIVal")]
public ref class Class1
{
private:
    int ival;
    String^ sval;

public:
    Class1()
    {
        ival = 5050;
        sval = "6040";
    }

    int GetIVal()
    {
        return ival;
    }

    String^ GetSVal()
    {
        return sval;
    }
};

O exemplo a seguir mostra como recuperar o membro padrão Recuperando o atributo personalizado para o membro padrão.

Dim classType As Type = GetType(Class1)
Dim attribType As Type = GetType(DefaultMemberAttribute)
Dim defMem As DefaultMemberAttribute = _
    CType(Attribute.GetCustomAttribute(CType(classType, MemberInfo), attribType), _
    DefaultMemberAttribute)
Dim memInfo() As MemberInfo = classType.GetMember(defMem.MemberName)
Type classType = typeof(Class1);
Type attribType = typeof(DefaultMemberAttribute);
DefaultMemberAttribute defMem =
    (DefaultMemberAttribute)Attribute.GetCustomAttribute((MemberInfo)classType, attribType);
MemberInfo[] memInfo = classType.GetMember(defMem.MemberName);
Type^ classType = Class1::typeid;
Type^ attribType = DefaultMemberAttribute::typeid;
DefaultMemberAttribute^ defMem =
    (DefaultMemberAttribute^)Attribute::GetCustomAttribute((MemberInfo^)classType, attribType);
array<MemberInfo^>^ memInfo = classType->GetMember(defMem->MemberName);

Pode ser mais simples usar o Type.GetDefaultMembers método, que produz o mesmo resultado. No entanto, GetDefaultMembers lança um InvalidOperationException se mais de um membro padrão é definido no tipo. O exemplo a seguir mostra a sintaxe para GetDefaultMembers.

Dim t As Type = GetType(Class1)
Dim memInfo() As MemberInfo = t.GetDefaultMembers()
Type t = typeof(Class1);
MemberInfo[] memInfo = t.GetDefaultMembers();
Type^ t = Class1::typeid;
array<MemberInfo^>^ memInfo = t->GetDefaultMembers();

Você também pode obter os atributos personalizados para um tipo e selecione apenas o DefaultMemberAttribute, usando o GetCustomAttributes método. O exemplo a seguir demonstra essa técnica.

Dim t As Type = GetType(Class1)
Dim customAttribs() As Object _
    = t.GetCustomAttributes(GetType(DefaultMemberAttribute), False)
If customAttribs.Length > 0 Then
    Dim defMem As DefaultMemberAttribute = CType(customAttribs(0), DefaultMemberAttribute)
    Dim memInfo() As MemberInfo = t.GetMember(defMem.MemberName)
    If memInfo.Length > 0 Then
        Console.WriteLine("Default Member: {0}", memInfo(0).Name)
    End If
End If
Type t = typeof(Class1);
object[] customAttribs = t.GetCustomAttributes(typeof(DefaultMemberAttribute), false);
if (customAttribs.Length > 0)
{
    DefaultMemberAttribute defMem = (DefaultMemberAttribute)customAttribs[0];
    MemberInfo[] memInfo = t.GetMember(defMem.MemberName);
    if (memInfo.Length > 0)
    {
        Console.WriteLine("Default Member: {0}", memInfo[0].Name);
    }
}
Type^ t = Class1::typeid;
array<Object^>^ customAttribs = t->GetCustomAttributes(DefaultMemberAttribute::typeid, false);
if (customAttribs->Length > 0)
{
    DefaultMemberAttribute^ defMem = (DefaultMemberAttribute^)customAttribs[0];
    array<MemberInfo^>^ memInfo = t->GetMember(defMem->MemberName);
    if (memInfo->Length > 0)
    {
        Console::WriteLine("Default Member: {0}", memInfo[0]->Name);
    }
}

Consulte também

Referência

DefaultMemberAttribute

Type.GetDefaultMembers

Conceitos

Exibindo informações de tipo