【发布时间】:2017-04-12 07:59:56
【问题描述】:
现在我正在开发一个简单的程序,这是我多次思考的问题。很多时候我运行我的方法两次,因为在运行它们之前检查返回值,我想知道是否有一种方法可以防止这种情况,比如使用我正在检查的方法的返回值。这很难解释,所以这里是我的程序中的一个真实示例。
public class SFDBRepository
{
public static Domain.SF.SFObject GetSFOrder(string WorkOrd)
{
//As you can see here i'm checking on the output of this method, before trying to return it.
if (Domain.SF.SF.GetOrder(WorkOrd) != null)
{
//If the value is not null (My method returns null if no result), return the object
return Domain.SF.SF.GetOrder(WorkOrd);
}
//Same thing happens here. My method runs twice every time almost.
else if(Domain.Building_DeliveryPerformance.Building_DeliveryPerformance.GetObject(WorkOrd) != null)
{
return Domain.Building_DeliveryPerformance.Building_DeliveryPerformance.GetObject(WorkOrd);
}
else
{
return null;
}
}
}
【问题讨论】:
-
将返回值捕获到一个变量中,之后使用该变量:
var result = Domain.ShopFloor.Shopfloor.GetOrder(WorkOrd) ... if (result != null) return result; -
您还应该考虑
usingdirective,这样您就不必在代码中重复使用整个命名空间路径。最好的做法是不要将类命名为与它们所在的命名空间相同。
标签: c# .net if-statement syntax