[英]C# return a jump statement from a function
作为所有编码人员,我讨厌重复的代码块,但作为 C++ 开发人员,我真的想要 null 检查,因为它已经被烧毁了,这意味着有很多块看起来像
if(object == null)
{
//For loops
continue;
//To check function inputs/creation
return; //maybe with a value
}
我知道我可以尝试/捕获所有内容,但我真的不喜欢这种编码风格
有没有办法用通用 function 替换 null 检查块。 就像是
jumpstatement CheckNull<T>(T thingToCheck)
{
if(thingToCheck == null)
{
return continue;
}
return null;
}
然后在实际代码中而不是旧的重复块中,我只有 function (根据要求填充)
for(int i = 0; i < myCollection.Count; i++){
//Function forces a "continue;" call if null
CheckNull(myCollection[i]);
//Do some stuff with myCollection[i]
}
我能看到的最接近的事情是谈论代码片段或内联函数,但我真的不认为那是我想要的。
我不认为你想在这里做什么是可能的。 基本上,您希望能够调用影响 function 中的控制流的 function调用它(例如,您希望能够从调用ZC1C425268E68385D1AB5074C17A94F 中返回)。 这对于普通的 function 是不可能的。
这种事情在 C/C++ 中使用类似函数的宏是可能的,在其他几种支持“真实”宏的语言中是可能的。 不幸的是,C# 没有宏,所以这种事情不能以你想要的方式完成。
C# 8 有一个更好的称为nullable reference types
的新功能。 您在这里和那里添加一些注释,然后编译器可以为您处理很多这样的事情。 您只需编写您想要编写的代码,而不必担心引用可能会意外地成为null
。 这需要一些时间来适应,但是一旦你掌握了这个概念,它就会非常酷。
除此之外,您不能返回任意跳转或转到...但您可以返回delegate
。 这类似于 C/C++ function 指针。 理论上,您可以使用它来转换此提议的调用:
CheckNull(someObject);
进入这个:
CheckNull(someObject)();
CheckNull()
的返回值是您要调用的方法。 但更实际地,它可能看起来更像这样:
CheckNull(someObject, o => {
//Do something with someObject here, where you can be **sure** someObject is not null
});
你甚至可以在你的方法中嵌入一个lock
来保持线程安全。
public void CheckNull<T>(T target, Action<T> action)
{
if (target is object)
{ //naive implementation -- potential thread race between these two lines
// ... but it does narrow the race to JUST those two lines, regardless of how much work is hidden in the action.
lock(target)
{
action(target);
}
}
}
您可以做的另一件事是使用Where()
操作。 所以如果你有一个这样的数组
object[] items = new object[100];
FillArray(items);
您可以编写这样的代码,仅对不是 null 的项目进行循环:
foreach(var item in items.Where(i => i is object))
{
//item will not be null, as long as you're in a single thread. Otherwise, lock on something first.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.