在方法内部打断标签
我有一个 switch 语句,它一遍又一遍地执行一些逻辑。 我想将其放入一个函数中,而不是使用剪切和粘贴,但我在这方面失败了。
这就是我想做的,但它无法编译,因为函数中的break标记不存在。 有人可以将其重构为更好的工作版本吗?
switch(param.ToString())
{
case "1":
BreakIfNotArgumentType<B>(param);
//do stuff
break;
case "2":
BreakIfNotArgumentType<BF>(param);
//do stuff
break;
}
private T BreakIfNotArgumentType<T>(object argumentObject)
{
if (argumentObject is T)
{
return (T)argumentObject;
}
else
{
break;
}
}
I have a switch statement that executes some logic over and over. Rather then use cut and paste I wanted to put it into a function, but I am failing badly at this.
This is what I want to do, but it does not compile because the break tag in the function does not exist. Can anyone refactor this to a better working version?
switch(param.ToString())
{
case "1":
BreakIfNotArgumentType<B>(param);
//do stuff
break;
case "2":
BreakIfNotArgumentType<BF>(param);
//do stuff
break;
}
private T BreakIfNotArgumentType<T>(object argumentObject)
{
if (argumentObject is T)
{
return (T)argumentObject;
}
else
{
break;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的函数本质上是复制
as
运算符的功能。as
运算符充当运行时安全的强制转换。 如果目标实例无法转换为目标类型,则分配空引用。 因此,它仅适用于引用类型。 最常见的用法是这样的...因为这在一个语句中给出了类型检查和转换操作。
您应该发布您的
switch
语句,我们也许能够更好地简化它。 尝试像您那样编写一个真正的内联函数(您期望它将函数中的代码替换为 switch 语句,这使其更像是宏而不是函数)是行不通的。Your function is essentially replicating the functionality of the
as
operator.The
as
operator functions as a runtime-safe cast. If the target instance can't be cast to the target type, then a null reference is assigned. Because of this, it will only work with reference types. The most common usage is like this...Because this gives the type checking and casting operation in one statement.
You should post your
switch
statement and we may be able to streamline it better. Trying to write a truly inline function as you had (where you were expecting it to substitute the code in the function into your switch statement, which makes it more of a macro than a function) won't work.如果参数无法转换,您可以让函数返回 null,或者抛出异常,以了解如何处理该部分代码的一些想法。
或者
You could have the function return a null if the argument can't be cast or throw an exception for a couple of ideas on how to handle that part of the code.
Or
让您的方法返回布尔值并检查返回值:
Make your method to return a boolean and check the return value:
如果您只有 2 个值可供比较 - 请改用 IF 语句
if you only have 2 values to compare with - use IF statement instead