2008年9月27日星期六

C# 中的 ?? 操作符有什么用?

场景介绍:

程序存储一些用户设定到一个文件中,这些设置被分为多个集合,分别包装成class,每个集合中的值项被定义为property。如果取propertynull,则可以认为文件中不存在该值得记录。

示例代码:

public class MySettings
{
public string NumOfPoints{ get; set; }
}

public class UserPreferences
{
public MySettings Settings{ get; set; }
}

class Program
{
static void Main(string[] args)
{
UserPreferences option = new UserPreferences();
string num = option.MySettings01 ?? 10; // only ONE line
}
}

class Program
{
static void Main(string[] args)
{
UserPreferences option = new UserPreferences();

// THREE lines!
string num = 10;
if( option.MySettings01 != null )
num = option.MySettings01.NumOfPoints;
}
}

总结:

C#中的操作符 ?? 在处理 property null 时可以简化代码。

没有评论: