Skip to content

Commit 3db16a2

Browse files
committed
Add DifferenceBetweenAsAndIs
1 parent d92233d commit 3db16a2

1 file changed

Lines changed: 91 additions & 0 deletions

File tree

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
namespace HelloDotNetGuide.CSharp语法
2+
{
3+
public class DifferenceBetweenAsAndIs
4+
{
5+
public static void IsOperator()
6+
{
7+
#region 检查对象是否是某个特定类型
8+
9+
string title = "Hello DotNetGuide";
10+
11+
if (title is string)
12+
{
13+
Console.WriteLine("是 string 类型");
14+
}
15+
else
16+
{
17+
Console.WriteLine("不是 string 类型");
18+
}
19+
20+
if (title is not null)
21+
{
22+
Console.WriteLine("不为 null");
23+
}
24+
else
25+
{
26+
Console.WriteLine("为 null");
27+
}
28+
29+
#endregion
30+
31+
#region 模式匹配
32+
33+
object obj = "追逐时光者";
34+
35+
if (obj is string str)
36+
{
37+
Console.WriteLine($" {str}");
38+
}
39+
else
40+
{
41+
Console.WriteLine("不是指定类型");
42+
}
43+
44+
#endregion
45+
46+
#region 列表模式
47+
48+
int[] empty = [];
49+
int[] one = [1];
50+
int[] odd = [1, 3, 5];
51+
int[] even = [2, 4, 6];
52+
int[] fib = [1, 1, 2, 3, 5];
53+
54+
Console.WriteLine(odd is [1, _, 2, ..]); // false
55+
Console.WriteLine(fib is [1, _, 2, ..]); // true
56+
Console.WriteLine(fib is [_, 1, 2, 3, ..]); // true
57+
Console.WriteLine(fib is [.., 1, 2, 3, _]); // true
58+
Console.WriteLine(even is [2, _, 6]); // true
59+
Console.WriteLine(even is [2, .., 6]); // true
60+
Console.WriteLine(odd is [.., 3, 5]); // true
61+
Console.WriteLine(even is [.., 3, 5]); // false
62+
Console.WriteLine(fib is [.., 3, 5]); // true
63+
64+
#endregion
65+
}
66+
67+
public static void AsOperator()
68+
{
69+
object title = "Hello DotNetGuide";
70+
string str = title as string;
71+
if (str != null)
72+
{
73+
Console.WriteLine("是 string 类型: " + str);
74+
}
75+
else
76+
{
77+
Console.WriteLine("不是 string 类型");
78+
}
79+
80+
int? num = title as int?;
81+
if (num.HasValue)
82+
{
83+
Console.WriteLine("是 int 类型: " + num.Value);
84+
}
85+
else
86+
{
87+
Console.WriteLine("不是 int 类型");
88+
}
89+
}
90+
}
91+
}

0 commit comments

Comments
 (0)