- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace CSharp基础
- {
- /// <summary>
- /// 可空类型的展示
- /// </summary>
- class 可空类型
- {
- public static void Main()
- {
- int? a = null;
- int? c = a * 5;
- // c = a * 5中因为a的值是null,所以c的值一定会是null
- if (c == null)
- {
- Console.WriteLine( "null");
- }
- //值为25
- a = 5;
- c = a * 5;
- Console.WriteLine(c);
- a = null;
- //在可空类型比较时,只要有一个操作数是null,则结果一定是false
- if (a > c)
- {
- Console.WriteLine("a>c");
- }
- else
- {
- Console.WriteLine( "a==null");
- }
- //空接合运算
- Console.WriteLine( "-----------------空接合运算--------------------------");
- //空接合运算符作用是处理 可空类型 与 引用类型
- // ?? 符号左边的数必须是 可空类型或者是引用类型,也就是必须是有可能==null的,值类型当然是不可以了
- // ?? 符号右连的数,必须是一个与左边数型相同的值,或者可以隐式转换的值.
- // 如果左边的数值不为null,则返回值是左连数,如果为null,则返回第二个数
- //b为可空类型
- int? b = null;
- //因为b==null则返回值是10
- int reInt = b ?? 10;
- //b为可空类型
- int? d = 20 ;
- //因为b<>null,则返回b的值,也就是20
- int reInt2 = d ?? 10;
- //其实以上??运算符类似与IsNull方法的执行
- int reInt3 = IsNull(b);
- int reInt4 = IsNull(d);
- Console.WriteLine( reInt );
- Console.WriteLine( reInt2);
- Console.WriteLine(reInt3);
- Console.WriteLine(reInt4);
- Console.WriteLine( "----------------引用类型的空接合运算演示--------------------");
- Person per = null;
- Person per2 = new Person();
- per2.name = "aladdin";
- Person rePer = per ?? per2;
- Console.WriteLine( rePer.name );
- Console.ReadLine();
- }
- public static int IsNull(int? par)
- {
- if (par == null)
- {
- return 10;
- }
- else
- {
- return (int)par;
- }
- }
- class Person
- {
- public string name;
- }
- }
- }
c# 中的可空类型与空接合运算
最新推荐文章于 2025-08-09 22:19:42 发布