有时我会在代码示例中看到这一点:
throw Error.ArgumentNull("someParameter");
这里有一个例子,在第 89 行。
我想Error
在我自己的代码中使用。我在哪里可以找到它?
(我试图自己找到它,我尝试using
了该文件顶部的命名空间,并试图让 Visual Studio 找到它,但到目前为止没有运气。)
它是由库的创建者定义的帮助器类,以使他们的生活更轻松。
错误.cs文件:
internal static ArgumentNullException ArgumentNull(string parameterName, string messageFormat, params object[] messageArgs)
{
return new ArgumentNullException(parameterName, Error.Format(messageFormat, messageArgs));
}
如果您正在寻找类似的功能,请查看Code Contracts(适用于 Visual Studio 的非 Express 版本)。然后你可以写这样的东西:
using System.Diagnostics.Contracts;
void MyMethod(string someParameter)
{
Contract.Requires<ArgumentNullException>(someParameter != null);
// ...
}
...and it will throw an exception at run-time when this condition has not been met.
It is an internal helper class, with internal
visibility. That's why you haven't been able to locate it.
Microsoft source code uses this pattern in a variety of places.
But why do it? It enables you to throw a consistent, nicely-formatted, localized exception without having to put that logic in every exception handler.
Taking that a step further, some definitions even contain compiler directives, such as:
internal static ArgumentException InvalidEnumArgument( string parameterName, int invalidValue, Type enumClass ) {
#if NETFX_CORE
return new ArgumentException(Error.Format(CommonWebApiResources.InvalidEnumArgument, parameterName, invalidValue, enumClass.Name), parameterName);
#else
return new InvalidEnumArgumentException( parameterName, invalidValue, enumClass );
#endif
}
Other methods (such as PropertyNull()
) are decorated with code analysis suppression messages.
Again, it's simply a convenience/consistency mechanism to avoid repeating this code all over the place.
I probably wouldn't suggest trying to use this exact code in your own project, because your needs will be different. But you can certainly use it as a pattern.
那是一个自定义的内部类型,它在 BCL 中不存在。
namespace System.Web.Http
{
/// <summary>
/// Utility class for creating and unwrapping <see cref="Exception"/> instances.
/// </summary>
internal static class Error
{}
}
你可以从那里复制它,如果你愿意的话。