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

Dus*_*sty 3 .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
   }
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 5

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

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

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

相反,使用过载可能会更清晰:

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

public string FindStuffAboutVehicle(string customer)
{
    return FindStuffAboutVehicle(customer, 
                                 new Vehicle { Make = "BMW", Year = 2011 });
}
Run Code Online (Sandbox Code Playgroud)

同样值得阅读Eric Lippert关于可选参数及其角落案例的帖子.