当前位置: 代码网 > it编程>编程语言>Asp.net > C#中?,??,??=,?: ,?. ,?[]各种问号的用法和说明详解

C#中?,??,??=,?: ,?. ,?[]各种问号的用法和说明详解

2025年11月26日 Asp.net 我要评论
前言在 c# 中,问号(?)远不止是一个简单的标点符号。随着语言版本的迭代更新,c# 围绕问号(?)发展出了一套强大而优雅的空值处理和条件表达机制。熟练掌握这些操作运算符不仅能大幅提升代码的简洁性和可

前言

在 c# 中,问号(?)远不止是一个简单的标点符号。随着语言版本的迭代更新,c# 围绕问号(?)发展出了一套强大而优雅的空值处理和条件表达机制。熟练掌握这些操作运算符不仅能大幅提升代码的简洁性和可读性,还能有效避免恼人的空引用异常,构建更加健壮的应用程序。

可空类型修饰符(?)

在 c# 中,值类型(如int、long、bool、datetime等)默认不能为null。使用 ? 修饰符,我们可以将值类型转换为可空类型。

            int notnullableint;// 非空int类型默认为 0
            int? nullableint = null;
            bool? nullablebool = null;
            long? nullablelong = null;
            datetime? nullabledate = null;

            // 检查是否有值
            if (nullableint.hasvalue)
            {
                console.writeline($"整数值: {nullableint.value}");
            }
            else
            {
                console.writeline("变量没有值(为null)");
            }

null 合并运算符(??)

null 合并运算符(??)如果左边的值不为null,则返回左边的值,否则返回右边的值。

        static void main(string[] args)
        {
            string username1 = "小明";
            string username2 = null;
            var getusername = username1 ?? username2 ?? "默认用户";

            console.writeline(getusername); // 输出: 小明

            string config1 = null;
            string config2 = null;
            string config3 = "defaultconfig";
            string finalconfig = config1 ?? config2 ?? config3 ?? "fallbackconfig";
            console.writeline(finalconfig); // 输出: defaultconfig
        }

null 合并赋值运算符(??=)

c# 8.0 引入的运算符,仅当左操作数为null时,才将右操作数的值赋给左操作数。这是懒加载模式的理想选择。

        static void main(string[] args)
        {
            string? name = null;
            name ??= "时光者";
            console.writeline(name); // 时光者

            name ??= "大姚"; // 不改变
            console.writeline(name); // 时光者


            //惰性初始化
            dictionary<string, string>? cache = null;

            cache ??= new dictionary<string, string>();
            cache["username"] = name;

            console.writeline(cache["username"]);
        }

三元条件运算符(?:)

条件运算符(?:),又称三元运算符,是一种简洁的条件表达式形式。它对布尔表达式进行求值,并根据结果为true或false,选择性地返回两个表达式中的对应结果,为简单条件判断提供了一种比传统if-else语句更紧凑、表达力更强的语法形式。

        static void main(string[] args)
        {
            int score = 80;
            string level = score >= 60 ? "pass" : "fail";
            console.writeline(level);
        }

null 条件成员访问运算符 (?.)

null 条件成员访问运算符 (?.) 在访问对象成员(属性、方法、字段等)前先检查对象是否为 null。如果对象为 null,整个表达式返回 null 而不会抛出 nullreferenceexception;如果对象不为 null,则正常访问成员。

        static void main(string[] args)
        {
            // 基本用法
            person person = null;
            string name = person?.name; // 不会抛出异常,name 为 null
            console.writeline(name ?? "name is null"); // 输出: name is null
        }

null 条件索引访问运算符 (?[])

null 条件索引访问运算符 (?[]) 在使用索引器访问集合元素前先检查集合对象是否为 null。如果集合为 null,整个表达式返回 null 而不会抛出异常;如果集合不为 null,则正常访问索引位置的元素。

        static void main(string[] args)
        {
            list<string> names = null;
            string firstname = names?[0]; // 不会抛出异常,firstname 为 null
            console.writeline(firstname ?? "no names available"); // 输出: no names available

            // 初始化列表后访问
            names = new list<string> { "时光者", "小袁", "大姚" };
            string secondname = names?[0]; // 安全访问索引为0的元素
            console.writeline(secondname); // 输出: 时光者
        }

到此这篇关于c#中?,??,??=,?: ,?. ,?[]各种问号的用法和说明详解的文章就介绍到这了,更多相关c# ?用法内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com