CallerMemberName in .NET 4.0 not working

别来无恙 提交于 2019-12-20 11:21:50

问题


I am trying to use CallerMemberName attribute in .NET 4.0 via BCL portability pack. It is always returning an empty string instead of the member name. What am I doing wrong?

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        MessageBox.Show(new class2().CallMe);
    }
}

public class class2
{
    public string CallMe 
    {
        get
        {
            return HelpMe();
        }
    }

    private string HelpMe([CallerMemberName] string param = "")
    {
        return param;
    }
}

回答1:


Targeting 4.0 works just fine if you add:

namespace System.Runtime.CompilerServices {
    sealed class CallerMemberNameAttribute : Attribute { }
}



回答2:


I found the solution, though it's not useful to me. You need to install KB2468871 on top of .NET Framework 4 to be able to use caller info attributes. Unfortunately, I can't ask each developer to remember to install it when they setup development environment.




回答3:


As I know, CallerMemberName is supported from .Net 4.5 You should not use it in .Net 4.0

Someone implemented this in .Net 4.0 using StackTrace. for example: http://www.journeyintocode.com/2013/04/callermembername-net-40.html

BUT, I do NOT recommend you to use the StackTrace since there could be a performance hit. Using StackTrace to get the caller name is very very slow. And this works in Debug, in release you cannot be sure whether StackTrace is "correct" or not.

So, my suggestion is: Just use CallerMemberName in .Net 4.5 or later version. In the early version of .Net, there isn't any foolproof or fast way of doing this.



来源:https://stackoverflow.com/questions/18840924/callermembername-in-net-4-0-not-working

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