呼び出し元のメソッド名を取得
- Apple
- 開発
あるメソッドを呼び出すメソッドの名前(または setter のプロパティ名)を使用したいことがときどきある。手動で文字列を渡すのも面倒なのでそれを自動化する方法。
Swift
これは知ってた。
func printCallerMethodName(callerMethodName: String = #function)
{
print("callerMethodName: \"\(callerMethodName)\"")
}
func awesomeMethod()
{
printCallerMethodName()
}
callerMethodName: "awesomeMethod()"
C#
ずっと C# でも同じようなことをしたくて、最近になってついに知ったから記事にするのだ。Swift でのやり方とペアで書いておけば検索しやすいだろうし。
void PrintCallerMethodName([CallerMemberName] string callerMethodName = null)
{
Console.WriteLine($"callerMethodName: \"{callerMethodName}\"");
}
void AwesomeMethod()
{
PrintCallerMethodName();
}
callerMethodName: "AwesomeMethod"
Share
リンクも共有もお気軽に。記事を書くモチベーションの向上に役立てます。