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);

}

相关推荐
AAA@峥2 小时前
Python 基础开篇:认识 Python、版本选择、环境部署与首个 HelloWorld
开发语言·python
李高钢2 小时前
WPF MVVM Light(三):RelayCommand 命令与 Messenger 消息
前端·c#·wpf
caimouse2 小时前
ReactOS 图形系统分析(47):GDI 批处理 — gdibatch.c
c语言·开发语言
qq21084629532 小时前
在python中什么是 self 和 cls?
开发语言·前端·python
杨充3 小时前
05.多用组合和少继承
开发语言·bash
傻啦嘿哟3 小时前
王者荣耀爬虫:爬取全英雄皮肤数据,用Python做可视化分析
开发语言·爬虫·python
AI直播技术杂谈3 小时前
直播画面突然模糊了,排查了三个小时
开发语言·php
菜冻鱼3 小时前
Python-pytorch-数据加载
开发语言·人工智能·pytorch·python·深度学习·机器学习