static void Main(string[] args)
{
Console.WriteLine(nameof(Program)); //编译时动作
Console.WriteLine(typeof(Program).Name);
Console.WriteLine(new Program().GetType().Name);
Console.WriteLine(new StackTrace().GetFrame(0).GetMethod().Name);
Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name);
Console.Read();
}
还可以从表达式中取名字
Console.WriteLine(GetPropertyName<Persion>(p => p.Age));
private static string GetPropertyName<T>(Expression<Func<T, object>> expr)
{
switch (expr.Body)
{
case MemberExpression memberExpression:
return memberExpression.Member.Name;
case UnaryExpression unaryExpression:
if (unaryExpression.Operand is MemberExpression expression)
{
return expression.Member.Name;
}
break;
default:
break;
}
return "";
}
CallerMemberName 特性
CallerMemberName 也是一个编译时的操作
编写
static void SetProperty([CallerMemberName] string propertyName = null)
{
Console.WriteLine(propertyName);
}
static void Main(string[] args)
{
SetProperty();
}
编译后
private static void SetProperty([CallerMemberName] string propertyName = null)
{
Console.WriteLine(propertyName);
}
private static void Main(string[] args)
{
SetProperty("Main");
}