Does CallerMemberNameAttribute use reflection

雨燕双飞 提交于 2021-01-02 05:26:16

问题


You can use the CallerMemberName attribute to avoid specifying the member name as a String argument to the called method when implementing INotifyPropertyChanged interface.

The question is does it use reflection behind the scene? Are there any performance hit over hard coding Property name?


回答1:


No; the compiler hard-codes the member-name directly during compilation. In terms of the IL, this is ldstr. For example if we compile:

static void Implicit()
{
    Log();
}
static void Explicit()
{
    Log("Explicit");
}
static void Log([CallerMemberNameAttribute] string name = null)
{}

we get:

.method private hidebysig static void Implicit() cil managed
{
    .maxstack 8
    L_0000: ldstr "Implicit"
    L_0005: call void Program::Log(string)
    L_000a: ret 
}
.method private hidebysig static void Explicit() cil managed
{
    .maxstack 8
    L_0000: ldstr "Explicit"
    L_0005: call void Program::Log(string)
    L_000a: ret 
}

As you can see - the IL has the name baked in directly exactly the same as if we put a string in manually.




回答2:


I've tried to decompile it and there's nothing in. So it doesn't look like the attribute itself uses reflection. In other hand it's placed in System.Runtime.CompilerServices that suggests that attribute itself is handled by the compiler in some special way so there shouldn't be any performance penalty.



来源:https://stackoverflow.com/questions/16053079/does-callermembernameattribute-use-reflection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!