.net之在 C# 4.0 中为可选参数提供默认值

artech 阅读:18 2024-11-24 20:56:43 评论: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 的帖子也值得一读.


标签:C#
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号