如何故意使用代码路径而不是 return C# 中的 int 值
How to purposely have a code path not return an int value in C#
问题:
我相信我在这里缺少编程的一些要点。我想创建一些方法,这些方法有一些 return 没有的代码路径。例如错误处理。
示例:
public static int calculateArea(int width, int length){
if(length < 0 || width < 0){
//don't want to return anything as negative distance is impossible
//Execute my error handling here
}
else{
int area = length * width;
return area;
}
}
问题: 很简单,有没有办法覆盖必须 return 所有代码路径中的值这一事实?
可能的解决方案 我在网上看到一个解决方案,其中错误处理代码路径 return 一个特定值,因此您知道要忽略它。然而,这似乎是一个非常不稳定的解决方案。
如果有更好的方法来编写这些类型的方法,我很乐意重构我的代码。
为什么这个问题是原创的:我认为这个问题是原创的,因为我一直无法在网上或 SO 论坛中找到具体的答案。
使用 Nullable Int 代替:int?
和 return null
当您不想 return 可用值时。
你要做的是在那里抛出一个异常。
Throw new Exception("Length and width cannot be negative.");
只要你把它放进去,你就会看到你的编译器错误消失了,因为在那个代码路径上,函数不是 returning - 它正在异常退出。
您还可以更具体地说明您的异常类型,也许使用 ArgumentException
。
异常表示函数不能对给定的参数进行操作,这是准确的。你不想 return null
。如果您这样做,那么任何调用该函数的东西都必须检查该值以查看它是否为空。如果它为空,那是什么意思?或者代码还是会抛出异常,但是现在莫名其妙NullReferenceException
。如果结果在被使用之前被传递了一点,异常可能离函数很远,这使得它更加混乱。但是如果在调用函数时使用无效参数抛出异常,那么就更容易判断问题出在哪里。
您必须 return 一个 int?,然后在该分支中 return null。否则你可以有一个 ref 参数并且如果长度或宽度为负数则不修改该值
如果您绝对必须 return 来自此方法的 int 并且不想 return 任何东西,那么唯一的选择是抛出未捕获的异常。 ArgumentOutOfRangeException 是个不错的选择
在 C# 中有两个语句被认为是 return 方法:return
和 throw
.
在您的情况下,如果距离为负,则应抛出 ArgumentException
或 ArgumentOutOfRangeException
。
另一方面,因为这是关于 参数验证 你应该看看 code contracts:
public static int CalculateArea(int width, int length)
{
Contract.Requires(length > -1 && width > -1, "Distance must be positive");
int area = length * width;
return area;
}
您可以抛出异常并直接或在代码中的其他位置捕获它。这是一个快速的、我认为不言自明的例子。
一些例子:
https://msdn.microsoft.com/en-us/library/87cdya3t(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/ms173163.aspx
public static void randomCaller()
{
try {
int a = calculateArea(-1, 500);
} catch(NegativeDistanceNotPossibleException e) {}
}
public static int calculateArea(int width, int length){
if(length < 0 || width < 0){
//don't want to return anything as negative distance is impossible
//Execute my error handling here
throw new NegativeDistanceNotPossibleException("this is not possible");
}
else{
int area = length * width;
return area;
}
}
public class NegativeDistanceNotPossibleException : Exception {
public NegativeDistanceNotPossibleException() {}
public NegativeDistanceNotPossibleException(string message) : base(message) {}
public NegativeDistanceNotPossibleException(string message, Exception inner) : base(message, inner) {}
}
如果你不想抛出异常,最好的方法是return一些class或者结构,显示操作结果。示例:
public class OperationResult
{
public bool Success {get;set}
public string ErrorMessage {get;set}
public int Result {get;set} //use it if success true
}
所以你可以处理错误文本和发生错误的事实,否则你可以使用操作结果
问题: 我相信我在这里缺少编程的一些要点。我想创建一些方法,这些方法有一些 return 没有的代码路径。例如错误处理。
示例:
public static int calculateArea(int width, int length){
if(length < 0 || width < 0){
//don't want to return anything as negative distance is impossible
//Execute my error handling here
}
else{
int area = length * width;
return area;
}
}
问题: 很简单,有没有办法覆盖必须 return 所有代码路径中的值这一事实?
可能的解决方案 我在网上看到一个解决方案,其中错误处理代码路径 return 一个特定值,因此您知道要忽略它。然而,这似乎是一个非常不稳定的解决方案。 如果有更好的方法来编写这些类型的方法,我很乐意重构我的代码。
为什么这个问题是原创的:我认为这个问题是原创的,因为我一直无法在网上或 SO 论坛中找到具体的答案。
使用 Nullable Int 代替:int?
和 return null
当您不想 return 可用值时。
你要做的是在那里抛出一个异常。
Throw new Exception("Length and width cannot be negative.");
只要你把它放进去,你就会看到你的编译器错误消失了,因为在那个代码路径上,函数不是 returning - 它正在异常退出。
您还可以更具体地说明您的异常类型,也许使用 ArgumentException
。
异常表示函数不能对给定的参数进行操作,这是准确的。你不想 return null
。如果您这样做,那么任何调用该函数的东西都必须检查该值以查看它是否为空。如果它为空,那是什么意思?或者代码还是会抛出异常,但是现在莫名其妙NullReferenceException
。如果结果在被使用之前被传递了一点,异常可能离函数很远,这使得它更加混乱。但是如果在调用函数时使用无效参数抛出异常,那么就更容易判断问题出在哪里。
您必须 return 一个 int?,然后在该分支中 return null。否则你可以有一个 ref 参数并且如果长度或宽度为负数则不修改该值
如果您绝对必须 return 来自此方法的 int 并且不想 return 任何东西,那么唯一的选择是抛出未捕获的异常。 ArgumentOutOfRangeException 是个不错的选择
在 C# 中有两个语句被认为是 return 方法:return
和 throw
.
在您的情况下,如果距离为负,则应抛出 ArgumentException
或 ArgumentOutOfRangeException
。
另一方面,因为这是关于 参数验证 你应该看看 code contracts:
public static int CalculateArea(int width, int length)
{
Contract.Requires(length > -1 && width > -1, "Distance must be positive");
int area = length * width;
return area;
}
您可以抛出异常并直接或在代码中的其他位置捕获它。这是一个快速的、我认为不言自明的例子。
一些例子: https://msdn.microsoft.com/en-us/library/87cdya3t(v=vs.110).aspx https://msdn.microsoft.com/en-us/library/ms173163.aspx
public static void randomCaller()
{
try {
int a = calculateArea(-1, 500);
} catch(NegativeDistanceNotPossibleException e) {}
}
public static int calculateArea(int width, int length){
if(length < 0 || width < 0){
//don't want to return anything as negative distance is impossible
//Execute my error handling here
throw new NegativeDistanceNotPossibleException("this is not possible");
}
else{
int area = length * width;
return area;
}
}
public class NegativeDistanceNotPossibleException : Exception {
public NegativeDistanceNotPossibleException() {}
public NegativeDistanceNotPossibleException(string message) : base(message) {}
public NegativeDistanceNotPossibleException(string message, Exception inner) : base(message, inner) {}
}
如果你不想抛出异常,最好的方法是return一些class或者结构,显示操作结果。示例:
public class OperationResult
{
public bool Success {get;set}
public string ErrorMessage {get;set}
public int Result {get;set} //use it if success true
}
所以你可以处理错误文本和发生错误的事实,否则你可以使用操作结果