C# - 如何使用空List<串GT;作为可选参数 [英] C#-How to use empty List<string> as optional parameter

查看:104
本文介绍了C# - 如何使用空List<串GT;作为可选参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以提供这样的例子吗?

Can somebody provide a example of this?

我曾尝试的String.Empty 和对象的初始化,但他们不工作,因为默认值有要在编译时常数

I have tried null,string.Empty and object initialization but they don't work since default value has to be constant at compile time

推荐答案

只需使用空合并运算符和空List的实例

Just use the null coalescing operator and an instance of empty List

public void Process(string param1, List<string> param2 = null) {
    param2 = param2 ?? new List<String>();
}

这样做的问题是,如果参数2为空,你分配一个新的参考那就不是在调用上下文访问。

The problem with this is that if "param2" is null and you assign a new reference then it wouldn't be accessible in the calling context.

这篇关于C# - 如何使用空List&LT;串GT;作为可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆