我正在使用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服务器宕机,那么它将执行空值检查并按其类型创建对象,以便我可以获得所需对象的默认值。
var first = rpc.GetObject(r => r?.First(a, b));
- NtFreX