.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 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/

相关文章:

java - C#/dot Net 和 Java 之间的 GZIP 输出和大小

c# - 我怎样才能改进这个设计?

c# - 如何使用反射将 DataTable 转换为 List<T>

winforms - 单独等待 IEnumerable<Task<T>> C#

multithreading - 并行收集处理的应用程序设计

c# - 加密和解密查询字符串导致附加未知文本

.net - 当我的进程被终止时到底发生了什么?

android - 使用任务修改控件时出现布局渲染错误

c# - ServiceStack + Swagger 以不同方式对资源进行分组的能力

optimization - 通过 XLS 操作提高性能