C#使用IF/ELSE语句中Method的返回值

Emi*_*sen 0 .net c# syntax if-statement

现在我正在制作一个简单的程序,这是我多次思考过的问题.很多次我运行我的方法两次是因为在运行它们之前检查返回值,我想知道是否有一种方法可以防止这种情况,比如使用我正在检查的方法返回的值.这很难解释,所以这是我的程序的真实例子.

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;
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

Jam*_*urt 6

您可以将其简化为以下代码,这些代码只调用一次这些方法并使代码更具可读性:

public class ShopFloorDBRepository
{
    public static Domain.ShopFloor.ShopFloorObject GetShopFloorOrder(string workOrd)
    {
        return Domain.ShopFloor.Shopfloor.GetOrder(workOrd) ??
               Domain.DG9_DeliveryPerformance.DG9_DeliveryPerformance.GetObject(workOrd);
    }
}
Run Code Online (Sandbox Code Playgroud)

解释为什么这有效 - ?? operator(null-coalescing operator!)基本上说"如果??左边的返回值为null,则返回右侧表达式的值".

这样您只需要调用一次函数.