开发者

How to get a property name?

This might seam like a strange question but....

public string MyProperty
{
    get
    {
        return "MyProperty";
    }
}

How can I replace the return statement 开发者_开发百科go it returns the property name without it being hard coded?


I wouldn't recommend doing this in general but here we go:

return MethodBase.GetCurrentMethod().Name.Substring(4);

Using an obfuscator can totally screw this up, by the way.


If you're using .NET, you can also use LINQ to identify this:

public static string GetName<T>(Func<T> expr)
{
  var il = expr.Method.GetMethodBody().GetILAsByteArray();
  return expr.Target.GetType().Module.ResolveField(BitConverter.ToInt32(il, 2)).Name; 
}

I can't claim credit for this solution - this came from here.


from C# 6, you can use nameof attribute to print the name of property or method name.

switch (e.PropertyName)
{
    case nameof(YourProperty):
    { break; }

    // instead of
    case "YourProperty":
    { break; }
}

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/nameof

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜