有的时候抛出一个异样,咱们须要晓得是哪个办法抛出的异样。那么,咱们能够通过传递 nameof 来获取调用者的办法名。然而,感觉很烦,每次都要传递 nameof。那么,有没有更好的办法呢?
CallerLineNumberAttribute
获取调用者的行号。
using System;
using System.Runtime.CompilerServices;
public static class Program
{public static void Main()
{TraceMessage("Something happened.");
}
public static void TraceMessage(string message,
[CallerLineNumber] int sourceLineNumber = 0)
{Console.WriteLine("Line: {0} - {1}", sourceLineNumber, message);
}
}
// The example displays the following output:
// Line: 10 - Something happened.
CallerFilePathAttribute
获取调用者的文件门路。
using System;
using System.IO;
using System.Runtime.CompilerServices;
public static class Program
{public static void Main()
{TraceMessage("Something happened.");
}
public static void TraceMessage(string message,
[CallerFilePath] string sourceFilePath = "")
{Console.WriteLine("File: {0} - {1}", Path.GetFileName(sourceFilePath), message);
}
}
// The example displays the following output:
// File: Program.cs - Something happened.
可发帖可群聊的技术交换形式曾经上线,欢送通过链接,退出咱们一起探讨。https://www.newbe.pro/links/
CallerMemberNameAttribute
获取调用者的办法名。
using System;
using System.Runtime.CompilerServices;
public static class Program
{public static void Main()
{DoProcessing();
}
public static void DoProcessing()
{TraceMessage("Something happened.");
}
public static void TraceMessage(string message,
[CallerMemberName] string memberName = "")
{Console.WriteLine("Member: {0} - {1}", memberName, message);
}
}
// The example displays the following output:
// Member: DoProcessing - Something happened.
CallerArgumentExpressionAttribute
获取调用者的参数表达式。C# 10.0 新增。
这个其实很好用,当前再也不必放心 ArgumentException 还须要写一个 nameof 了。
using System;
using System.Runtime.CompilerServices;
public static class Program
{public static void Main()
{
int x = 10;
int y = 20;
Assert(x > y, "x > y");
}
public static void Assert(bool condition, [CallerArgumentExpression("condition")] string message = null)
{Console.WriteLine("Condition: {0} - {1}", condition, message);
}
}
// The example displays the following output:
// Condition: False - x > y
总结
通过下面的几个例子,咱们能够看到,借助在编译时获取调用者的行号、文件路劲和调用者办法名的个性,咱们能够在开发中更加不便的进行日志记录。
参考
- CallerLineNumberAttribute Class1
- CallerFilePathAttribute Class2
- CallerMemberNameAttribute Class3
- CallerArgumentExpressionAttribute Class4
感谢您的浏览,如果您感觉本文有用,请点赞、关注和转发。
可发帖可群聊的技术交换形式曾经上线,欢送通过链接,退出咱们一起探讨。https://www.newbe.pro/links/
- 本文作者:newbe36524
- 本文链接:https://www.newbe.pro/Others/0x01D-I-don-t-want-to-pass-nameof-anymore/
- 版权申明:本博客所有文章除特地申明外,均采纳 BY-NC-SA 许可协定。转载请注明出处!
- https://learn.microsoft.com/d… ↩
- https://learn.microsoft.com/d… ↩
- https://learn.microsoft.com/d… ↩
- https://learn.microsoft.com/d… ↩