以前的写法:
void Foo(Bar bar)
{
if (bar == null)
{
throw new ArgumentNullException("bar");
}
}
透过这种方式,就不需要写死 "bar" 字符串。当我们重命名 bar 时,程式也能正常的反应正确的名称。
Nameof 可以用於取得:类名、方法名、参数名、属性(Attribute)名。
例子如下:
public class MyClass
{
public static void Show(int age)
{
Console.WriteLine(nameof(MyClass)); // 输出 MyClass 类名
Console.WriteLine(nameof(Show)); // 输出 Show 方法名
Console.WriteLine(nameof(age)); // 输出 age
Console.WriteLine(nameof(TestMethodAttribute)) // 输出 Attribute 名
}
}
得到当前类名:类的名称字符串值
public class MyClass
{
public void Show()
{
Console.WriteLine(this.GetType().Name); // 输出"MyClass"
}
public static void Set()
{
Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().ReflectedType.FullName); // 如果是静态方法里,输出"MyClass"
}
}
获取当前函数名称
public class MyClass
{
public void Show()
{
//获取当前函数名称
Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name); // 输出"Show"
}
}
获取类中的方法或者字段或者属性是谁调用了
public class MyClass
{
void Init()
{
Show() ;
}
public void Show()
{
//调用函数的名称:获取谁调用的我
Console.WriteLine(new StackTrace().GetFrame(1).GetMethod()); // 输出"void Init()"
}
}
U3d中活动详细输出详细:
public class MyClass : MonoBehaviour
{
void Init()
{
//非静态函数版本
string CallStack = "CallStack:[" + new StackTrace().GetFrame(1).GetMethod() + "] => ";
string SceneName = " Scene:[" + SceneManager.GetActiveScene().name + "]";
string GameObjectName = " GameObject:[" + gameObject.name + "]";
string ClassName = " Class:[" + this.GetType().Name + "]";
string FunctionName = " Function:[" + System.Reflection.MethodBase.GetCurrentMethod().Name + "]";
string Log = " Log:[" + "runing" + "]";
string OutputResult = CallStack + SceneName + GameObjectName + ClassName + FunctionName + Log;
Debug.Log(OutputResult);
}
public static void Show(GameObject go)
{
//静态函数版本
string callStack = "CallStack:[" + new StackTrace().GetFrame(1).GetMethod() + "] => ";
string FileName = " FileName:[" + System.IO.Path.GetFileName(new System.Diagnostics.StackTrace(1, true).GetFrame(0).GetFileName()) + "]";
string LineNumber = " Line:[" + new System.Diagnostics.StackTrace(1, true).GetFrame(0).GetFileLineNumber().ToString() + "]";
string sceneName = " Scene:[" + SceneManager.GetActiveScene().name + "]";
string gameObjectName = " GameObject:[" + go.name + "]";
string className = " Class:[" + System.Reflection.MethodBase.GetCurrentMethod().ReflectedType.FullName + "]";
string functionName = " Function:[" + System.Reflection.MethodBase.GetCurrentMethod().Name + "]";
string log = " Log:[" + "GetComponentNullLogError" + "]";
string OutputResult = callStack + FileName + LineNumber + sceneName + gameObjectName + className + functionName + log;
Debug.LogError(OutputResult);
}
}
//运行效果:
CallStack:[Void On_EnterFirst_SceneLoaded()] => Scene:[EnterFirstScene] GameObject:[LeiGong_01(Clone)] Class:[MoveNavMeshAgent] Function:[Init] Log:[runing]