是一个纯写入记录器的方法
本文关键字:记录器 方法 一个 | 更新日期: 2023-09-27 18:09:27
纯方法定义为"不引起任何可见的状态变化"。
我的方法是写一个日志消息,如果一个参数为空或抛出异常。它还纯洁吗?写入记录器是一个可见的更改吗?
代码如下:
/// <summary>
/// Formats with invariant culture - won't throw an exception.
/// </summary>
/// <param name="format">A composite format string.</param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
/// <returns>A copy of format in which the format items have been replaced by the string representation of the corresponding objects in args.</returns>
[SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "CyanCor.Core.Logging.Log.ExceptionPrevent(System.String,System.String,System.Int32,System.String)", Justification = "It is for the logger (riedl)")]
[Pure - yes or no?]
public static string FormatSafe(this string format, params object[] args)
{
if (format == null)
{
Log.ExceptionPrevent("Argument format is null");
return NullFormat;
}
try
{
return string.Format(CultureInfo.InvariantCulture, format, args);
}
catch (ArgumentException exc)
{
Log.Exception(exc);
return format;
}
catch (FormatException exc)
{
Log.Exception(exc);
return format;
}
}
一般来说,"状态改变"是指修改对象的状态,即:修改变量或改变复杂对象的结构。按照这个定义,您的方法似乎仍然是纯的。