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

问题描述

有人可以提供一个例子吗?

Can somebody provide a example of this?

我尝试过 nullstring.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<string>

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

    // or starting with C# 8
    param2 ??= new List<string>();
}

这样做的问题是,如果param2"为空并且您分配了一个新引用,那么它将无法在调用上下文中访问.

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<string>作为可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 19:46