C#:函数参数指定默认值

在C#中,可以为函数参数指定默认值,这样调用函数时可以不传递该参数,而是使用默认值。这对于简化API调用和提高代码的可读性非常有帮助。从C#6.0开始,可以直接在方法签名中为参数指定默认值,而不需要使用可选参数的特性(`Optional`)。

示例

假设有一个计算折扣价格的函数,可以为折扣率参数设置一个默认值,例如10%的折扣。

示例代码(C#6.0及以后)

public class Product

{

public string Name { get; set; }

public decimal Price { get; set; }

}

public class DiscountCalculator

{

public decimal CalculateDiscountedPrice(decimal price, decimal discountRate = 0.1m)

{

return price * (1 - discountRate);

}

}

在上面的代码中,`CalculateDiscountedPrice` 方法接受两个参数:`price` 和 `discountRate`。`discountRate` 有一个默认值 `0.1m`,这意味着如果在调用这个方法时没有提供 `discountRate`,它将默认使用10%的折扣率。

使用示例

var calculator = new DiscountCalculator();

var product = new Product { Name = "Example Product", Price = 100m };

// 使用默认折扣率10%

var priceWithDefaultDiscount = calculator.CalculateDiscountedPrice(product.Price);

Console.WriteLine($"Price with default discount: {priceWithDefaultDiscount}");

// 指定一个不同的折扣率

var priceWithCustomDiscount = calculator.CalculateDiscountedPrice(product.Price, 0.2m); // 20%折扣率

Console.WriteLine($"Price with custom discount: {priceWithCustomDiscount}");

注意事项

  • 默认值只能是常量表达式:默认值必须是编译时常量,例如字面量或常量字段。它不能是运行时计算得出的值或依赖于其他参数的值。

  • 从C#7.1开始:可以为引用类型参数提供 `null` 作为默认值,例如 `string name = null`。这在希望明确区分"未设置"和"空字符串"的情况时特别有用。

  • 可选参数:尽管从C#6.0开始可以在方法签名中直接指定默认值,但如果使用的是早期版本的C或者出于某种原因需要使用旧式的可选参数语法,可以这样做:

public decimal CalculateDiscountedPrice(decimal price, Optional decimal discountRate = 0.1m)

{

return price * (1 - discountRate);

}

相关推荐
小oo呆31 分钟前
【学习心得】Python函数参数中的两个特殊分隔符
开发语言·python
x10n937 分钟前
微软 VC++ 运行库合集VCRedistPack
开发语言·c++·microsoft·vc++运行库·dll报错
qz_Serene41 分钟前
C++:string(底层,常用接口,具体题目,模拟实现)
开发语言·c++
NiceBlueChai42 分钟前
Qt 跨线程传递多容器嵌套结构:一次 Release 实测
开发语言·qt
念何架构之路42 分钟前
go-grpc逻辑架构图
开发语言·后端·golang
SEO_juper44 分钟前
AI 爬虫 robots.txt 检查工具:你的站是不是把 AI 挡在门外了
开发语言·人工智能·爬虫·python·外贸独立站
木圭的AI时代指南1 小时前
实测 MiniMax M3.1 Flash:同一道 Three.js 大题,两个 agent 差出 4.6 倍
开发语言·javascript·ecmascript
星恒讯工业路由器1 小时前
工业路由器在中小 IoT 场景的选型与适配实践:从标准品到定制化的技术路径
开发语言·网络·物联网·php·工业路由器选型·工业网关odm·链路冗余切换
OKkankan1 小时前
python 进阶(三):面向对象进阶——从“会写 class”到设计可维护的后端对象
开发语言·数据结构·python