VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 编程开发 > C#编程 >
  • C#教程之C# 8 - Nullable Reference Types 可空引用类型(3)

现在可以看到,这些属性都出现了波浪线的警告,如果我们build一下这个项目,那么也会出现很多警告: 

Show output from: Build 
' •n 'void printperson(person 
Rebuild All 
starte 
c: (30, 
1>Pro 
c: (31, 
1>Pro 
c: (24, 
1>Pro 
c: (25, 
1>Pro 
cs(ll, 
1>Pro 
cs(12, 
1>Pro 
n: 1 Appl — 
1>C0 
ne building 
Rebul 
23, 30, 31) 
23, 31, 27) 
23, 24, 27) 
24, 25, 31) 
29, 11, 33) 
25, 12, 31) 
warm 
warm 
warm 
warm 
warm 
warm 
d project: ConsoleÅppl, 
ng CS8618: 
ng CS8618: 
ng CS8618: 
ng CS8618: 
ng cs8600: 
ng CS8604: 
guy at 1 on: 
ble property ' 
ble proper 
ble proper 
ty 
ble proper 
ty 
Debug 
k-,y CPU 
ci ty' 
e 
Address' is 
s 'minitialized C n 
s 'minitializeå 
s 'minitializeå 
'minitialized C n 
for 
Consi der 
to non—null a 
1 ill 
r declaring the 
declaring the pr 
C n d declaring the pr 
r declaring the 
ble type 
property as null able 
operty as nullablæ 
operty as nullablæ 
property as null able 
Converting null lit al or possible null due 
\Cons01eÅppl 0\Conso e 
project "ConsoleÅppL c 
'Id All: 1

这是因为我们把这两个类的成员声明称了非null的引用类型,而我却没有对它们进行初始化。 

 

成员可能是null 

如果我想让这些成员可以为null(意图上),那么就需要把它们设置为可null的(意图),在类型后边加上问号“?”即可: 

2 references 
public class Person 
O references 
{ get; 
public string? 
Name 
I reference 
public Address? Address { 
I reference 
public class Address 
I reference 
public string? Province { 
O references 
City 
public string? 
get; 
set; } 
get; set; 
get; set; 
set;

 

再次build项目之后,警告都没有了: 

Show output from: Build 
Rebuild started: projec 
I >Cons01eÅppl — 
Rebuild All: 1 succeeded, 
ConsoleÅppl, 
gurati on: 
Debug kny CPU 
\Cons01eÅppl nso e 
0 1 ill

 

然后再看一下这个方法: 

相关教程