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
精彩评论