简体   繁体   中英

How does CallerMemberName work from inside?

I cannot find any documentation or at least an explanation of how attributes like this work from inside.

    [CallerMemberName] 
    [CallerFilePath] 
    [CallerLineNumber]

Documentation I found shows only how to use it.

Is it possible to create your own implementation of [CallerMemberNameAttribute] or some custom [CallerObjectAttribute]?

It's interesting for me just for learning purposes and understanding of the code behind.

So just for learning purposes. The attributes itself do nothing to the method itself, but to the way it is called.

If the compiler has to create a call to the method, he checks every parameter, if it has one of theses attributes, if so, it passes the name or the file of the caller as parameter value. It overwrites the default value, by an other default value. The requirement of placing the default parameter there is only, to let the compiler allow you to omit this parameter in first place.

Suppose you have code like this:

   static void Main(string[] args)
    {
        Test();
        Test1();
    }

    public static void Test(string name = "")
    {
        Console.WriteLine(name);
    }

    public static void Test1([CallerMemberName] string name = "")
    {
        Console.WriteLine(name);
    }

The code generated is the same as for

  static void Main(string[] args)
    {
        Test("");
        Test1("Main");
    }

You cannot emulate this anyhow with your programming, unless you modify the compiler itself. It's the compiler of the caller who puts in this "Main" string, (or the name of the file currently compiled) if it finds this attribute.

If you pass the value of the parameter explicitly, as on the last line of the code sample, both, the default value and the CallerMemberName Attribute will be ignored.

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