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

5 c# rpc 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();
}
Run Code Online (Sandbox Code Playgroud)

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

public FirstObj First(string one, string two)
{
    return rpc.First(one, two);
}
Run Code Online (Sandbox Code Playgroud)

哪个会进行空检查,如果RPC服务器关闭,它会按类型创建对象,所以我将得到所需对象的默认值.

Mak*_*kin 4

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

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

对于这种用法:

var first = rpc.GetObject(r => r.First(a, b));
Run Code Online (Sandbox Code Playgroud)