1 参数有效性检查
编写业务逻辑时,从鲁棒性的角度出发,需要对方法的参数进行有效性检查,比如空值检查、空字符串检查、字符串长度检查、范围检查等。
using System;
namespace ConsoleApp1
{
/// <summary>
/// Guard类有两个静态方法,分别对空对象和空字符进行判断(静态方法不需要实例化即可调用)。
/// </summary>
class Guard
{
public static void NotNull(object param, string paramName)
{
if (param is null)
{
ArgumentNullException argNullException = new ArgumentNullException(paramName);
throw new Exception(String.Format("Parameter '{0}' cannot be null!", paramName), argNullException);
//throw new ArgumentNullException(paramName);
}
}
public static void NotNullorEmpty(string param, string paramName)
{
NotNull(param, paramName);
if (param == string.Empty)
{
ArgumentException argException = new ArgumentException(paramName);
throw new Exception(String.Format("String '{0}' cannot be empty!", paramName), argException);
//throw new ArgumentException($"The string cannot be empty.", paramName);
}
}
}
/// <summary>
/// Test类用于测试Guard类,或者说,Test类展示了Guard类的使用方法。
/// </summary>
class Test
{
Guard guard;
public Test()
{
this.guard = new Guard();
}
public void TestNotNull(string str)
{
Guard.NotNull(str, nameof(str));
}
public void TestNotNullorEmpty(string str)
{
Guard.NotNullorEmpty(str, nameof(str));
}
}
class Program
{
static void Main(string[] args)
{
Test test = new Test();
//test.TestNotNull(null);
string tmp = string.Empty;
test.TestNotNullorEmpty(tmp);
}
}
}
2 可操作性
编程的时候,任何可能会出错的操作,都要try…catch…一下,比如往串口写数据。
参考链接
1.C# 9.0 新特性之参数非空检查简化
2.C#检验参数合法性公用方法