c# custom attribute for a method parameter
I would like to understand how this particular case works. Here is the shot from msdn article where INotifyPropertyChanged interface is explained (https://msdn.microsoft.com/query/dev12.query?appId=Dev12IDEF1&l=EN-US&k=k%28System.ComponentModel.INotifyPropertyChanged%29;k%28TargetFrameworkMoniker-.NETFramework,Version%3Dv4.5%29;k%28DevLang-csharp%29&rd=true)
As it's said in marked lines there is a way of intercepting method call to substitute a value instead of what is actual goes as a parameter? I would like to get an idea of what the code to do this looks like. I know how to work with attributes set for properties and other class members but this use case is not clear for me.
Thanks.
It seems to be a feature implemented in the compiler: it knows about this special attribute and it substitutes the name of the caller into the optional argument when it has its default value.
If you want you can check the Roslyn implementation. Although it is not always very straightforward to navigate there seems to be something here in the GetDefaultParameterValue
function (starting at line 844, at least in the current revision as of the time of writing -- 0db946b
):
if the optional parameter is annotated with <see cref="CallerLineNumberAttribute"/>
, <see cref="CallerFilePathAttribute"/>
or <see cref="CallerMemberNameAttribute"/>
, and there is no explicit argument corresponding to it, we will provide caller information as a value of this parameter.
At line 912 there is an else if
clause that handles this case (the if
and else if
clauses before that handle the similar new features CallerLineNumberAttribute
and CallerFilePathAttribute
):
...
else if (parameter.IsCallerMemberName && ((callerSourceLocation = GetCallerLocation(syntax, enableCallerInfo)) != null))
...
which is eventually used to bind the parameter:
BoundExpression memberNameLiteral = MakeLiteral(syntax, ConstantValue.Create(memberName), _compilation.GetSpecialType(SpecialType.System_String));
defaultValue = MakeConversion(memberNameLiteral, parameterType, false);
链接地址: http://www.djcxy.com/p/30482.html
上一篇: 使用TypeScript和Babel的Gulp源地图
下一篇: 方法参数的c#自定义属性