C# 带有空检查的重复代码

C# Repetitive code with null check

我正在使用 RPC(protobuf-remote),我需要做一些检查以防另一端(服务器)出现故障。假设我有很多 RPC 方法,例如:

public FirstObj First(string one, string two)
{
    if (rpc == null)
        return (FirstObj)Activator.CreateInstance(typeof(FirstObj));

    return rpc.First(one, two);
}

public SecondObj Second(string one)
{
    if (rpc == null)
        return (SecondObj)Activator.CreateInstance(typeof(SecondObj));

    return rpc.Second(one);
}

public ThirdObj Third()
{
    if (rpc == null)
        return (ThirdObj)Activator.CreateInstance(typeof(ThirdObj));

    return rpc.Third();
}

有没有办法改变这个重复的空检查代码?所以我可以这样写:

public FirstObj First(string one, string two)
{
    return rpc.First(one, two);
}

如果 RPC 服务器关闭,它将执行空值检查并根据其类型创建对象,因此我将获得所需对象的默认值。

您可以使用泛型方法简化您的代码:

private static T Make<T>() {
    return (T)Activator.CreateInstance(typeof(T));
}
public FirstObj First(string one, string two) {
    return rpc == null ? Make<FirstObj>() : rpc.First(one, two);
}
public SecondObj Second(string one) {
    return rpc == null ? Make<SecondObj>() : rpc.Second(one);
}
public ThirdObj Third() {
    return rpc == null ? Make<ThirdObj>() : rpc.Third();
}

如果 FirstObjSecondObjThirdObj 类型都是 类,而不是 struct 或基元,并且 rpc 永远不会returns null 对他们来说,你可以这样做:

public static T RpcOrDefault<T>(T obj) where T : class {
    return obj ?? (T)Activator.CreateInstance(typeof(T));
}

并称之为

FirstObj first = RpcOrDefault(rpc?.First(one, two));
//                               ^

请注意 ?. 中的 ?,它使您免受 null 引用异常的影响。

您可以创建这样的扩展方法:

public static class RpcExtension
{
    public static T GetObject<T>(this RPC rpc, Func<RPC, T> func)
        where T: class , new ()
    {
        if (rpc == null)
        {
            return Activator.CreateInstance<T>();
        }
        return func(rpc);
    }
}

对于这种用法:

var first = rpc.GetObject(r => r.First(a, b));