c# - 如果对象不为空,则将对象添加到列表的简写

标签 c# list null shorthand

假设我在 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/

相关文章:

c# - C# 中是否有像 Dictionary<> 这样的类,但只有键,没有值?

swift - 无法在 View Controller 和 TableView Controller 之间快速发送 int 值

c# - .NET Framework - 有什么方法可以让 Dictionary<> 更快一点?

python - 是否可以创建 "def"的列表?

c# - .NET WSE 客户端 stub 是线程安全的吗?

list - 如何有效地从索引开始获取 Tcl 列表的其余部分?

ios - 如何在 Swift 中对对象进行 Nil

c - 如何使用英特尔 C 编译器为双函数返回 NULL?

c# - Xamarin Forms 显示警报消失

C# 语法 :----- IEnumerable<Person> people = new List<Person>();