问题
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