.net 为C#4.0中的可选参数提供默认值
如果其中一个参数是自定义类型,如何设置默认值.net 为C#4.0中的可选参数提供默认值,.net,c#-4.0,.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 FindStuffAboutVeh
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 });
}
埃里克·利珀特的文章也值得一读