如果其中一个参数是自定义类型,我该如何设置默认值?
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
}
}
最佳答案
你不能,真的。但是,如果您不需要 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 的帖子也值得一读.
关于.net - 在 C# 4.0 中为可选参数提供默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6584615/