为C#4.0中的Optional参数提供默认值

时间:2011-07-05 14:48:13

标签: .net c#-4.0

如果其中一个参数是自定义类型,如何设置默认值?

public class Vehicle
{
   public string Make {set; get;}
   public int Year {set; get;}
}

public class VehicleFactory
{
   //For vehicle, I need to set default values of Make="BMW", Year=2011
   public string FindStuffAboutVehicle(string customer, Vehicle vehicle)
   {
       //Do stuff
   }
}

1 个答案:

答案 0 :(得分:5)

你不能,真的。但是,如果您不需要null表示其他任何内容,您可以使用:

public string FindStuffAboutVehicle(string customer, Vehicle vehicle = null)
{
    vehicle = vehicle ?? new Vehicle { Make = "BMW", Year = 2011 };
    // Proceed as before 
}

在某些情况下,这很好,但它确实意味着你不会发现调用者意外传递null的情况。

使用过载可能更清晰:

public string FindStuffAboutVehicle(string customer, Vehicle vehicle)
{
    ...
}

public string FindStuffAboutVehicle(string customer)
{
    return FindStuffAboutVehicle(customer, 
                                 new Vehicle { Make = "BMW", Year = 2011 });
}

阅读Eric Lippert关于optional parameters and their corner cases的帖子也是值得的。