如果其中一个参数是自定义类型,如何设置默认值?
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
}
}
答案 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的帖子也是值得的。