假设我在 c# 中有以下内容:
List<Foo> fooList = new();
Foo fooObject;
以下内容是否存在简写?
if(fooObject != null)
{
fooList.Add(fooObject);
}
根据我的代码中的情况,fooObject
可能为空或不为空,但如果不为空,我想将其添加到fooList
中。
就我的研究而言,空合并或三元运算符的可能性都没有涵盖上述可能性。
最佳答案
我能想到的唯一解决方案是使用扩展方法
public class Foo
{
}
static class Program
{
static void Main(string[] args)
{
List<Foo> list = new List<Foo>();
Foo item = null;
list.AddNotNull(item);
item = new Foo();
list.AddNotNull(item);
}
public static void AddNotNull<T>(this IList<T> list, T item) where T : class
{
if (item != null)
{
list.Add(item);
}
}
}
关于c# - 如果对象不为空,则将对象添加到列表的简写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73886936/