简体   繁体   中英

DefaultMemberAttribute - what does it do?

I've already read the MSDN article about it. It seems internally it is the way c# sets which is the function that is going to work as indexer(am I right?). Now, I've seen the following example:

[DefaultMemberAttribute("Main")]
public class Program {

    public static void Main() {
        ...
    }
}

Now, I don't get it what it means.


Thanks all. But I still can't get its usefulness, apart from the indexer thing. When are we going to call InvokeMember?

No, the DefaultMemberAttribute is used by languages such as VB.NET to find out the member that is acted on by default if no member is referenced from an object, ie the member invoked by InvokeMember . This is often used in conjunction with indexers, as you noted, but it is not used by C# directly (unless you use InvokeMember explicitly).

However, for the benefit of other .NET languages, C# does emit the DefaultMemberAttribute for the indexer of a class (if it has one), as indicated by MSDN :

The C# compiler emits the DefaultMemberAttribute on any type containing an indexer. In C# it is an error to manually attribute a type with the DefaultMemberAttribute if the type also declares an indexer.

I think MSDN confuses things by referring to indexers a lot in the remarks but then giving an example that does not use an indexer. To clarify, the default member can be anything, but C# gives special behavior for indexers by emitting the attribute for you (if an indexer exists) to the exception of all other use cases.

I personally have never used it, but as far as I can tell you are defining the default method to be invoked when calling InvokeMember . So, using the code snippet you provided if I was to say:

Program prog = new Program();
typeof(Program).InvokeMember("", null, null, prog, null);

Because I left the first argument empty of the InvokeMember call it would use the attribute to determine what the default member is of your class, in your case it is Main.

The DefaultMemberAttribute attribute defines the default member to be called on a when InvokeMember is called with an empty string as the first argument.

If you read the MSDN docs for InvokeMember , it explicitly says:


name
Type: System.String
The String containing the name of the constructor, method, property, or field member to invoke.
-or-
An empty string ("") to invoke the default member.

The default member will be the one declared by the DefaultMemberAttribute attribute.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM