在C#中?操作符相信大家都不会陌生了吧,是可空类型。
int i = 5;
//int j = null;//会报错,Cannot convert null to 'int' because it is a non-nullable value type
int? k = null;//使用?操作符来定义可空类型就不会报错了
Console.WriteLine(i);
//Console.WriteLine(j);
Console.WriteLine(k);
//int j = null;//会报错,Cannot convert null to 'int' because it is a non-nullable value type
int? k = null;//使用?操作符来定义可空类型就不会报错了
Console.WriteLine(i);
//Console.WriteLine(j);
Console.WriteLine(k);
那么,??又是什么东西呢?
??判断表达式左侧是否为null,如果左侧为null就返回??右侧的值,否则就返回左侧值。
int? num1 = 55;
int? num2 = null;
string str1 = "Hello";
string str2 = null;
int result1 = num1 ?? 0;
int result2 = num2 ?? 0;
string result3 = str1 ?? "It was null";
string result4 = str2 ?? "It was null";
Console.WriteLine(result1.ToString() + "\r\n");//输出结果:55
Console.WriteLine(result2.ToString() + "\r\n");//输出结果:0
Console.WriteLine(result3.ToString() + "\r\n");//输出结果:Hello
Console.WriteLine(result4.ToString() + "\r\n");//输出结果:It was null
int? num2 = null;
string str1 = "Hello";
string str2 = null;
int result1 = num1 ?? 0;
int result2 = num2 ?? 0;
string result3 = str1 ?? "It was null";
string result4 = str2 ?? "It was null";
Console.WriteLine(result1.ToString() + "\r\n");//输出结果:55
Console.WriteLine(result2.ToString() + "\r\n");//输出结果:0
Console.WriteLine(result3.ToString() + "\r\n");//输出结果:Hello
Console.WriteLine(result4.ToString() + "\r\n");//输出结果:It was null
顺便再说一下,VS2008中利用Linq读取XML文件,里面涉及到上面提及到的操作符了.
XDocument contactFile = XDocument.Load(Server.MapPath("~/contacts.xml"));
var contacts = from c in contactFile.Descendants("Contact")
select new
{
Name = (string)c.Element("Name"),
Title = (string)c.Element("Title"),
Email = ((string)c.Element("Email")).Replace("@", "#"),
Age = (int)c.Element("Age"),
YearAtCompany = (int?)c.Element("YearAtCompany")??0
//哈哈,这儿?与??都用到了啊
//注意:如果没有?则在xml中如果没有这个节点就会报错拉
//如果没有??则当没有这个节点的时候就会显示空值
};
GridView1.DataSource = contacts;
GridView1.DataBind();
var contacts = from c in contactFile.Descendants("Contact")
select new
{
Name = (string)c.Element("Name"),
Title = (string)c.Element("Title"),
Email = ((string)c.Element("Email")).Replace("@", "#"),
Age = (int)c.Element("Age"),
YearAtCompany = (int?)c.Element("YearAtCompany")??0
//哈哈,这儿?与??都用到了啊
//注意:如果没有?则在xml中如果没有这个节点就会报错拉
//如果没有??则当没有这个节点的时候就会显示空值
};
GridView1.DataSource = contacts;
GridView1.DataBind();
xml文件如下:
<?xml version="1.0" encoding="utf-8" ?>
<Contacts>
<Contact>
<Name>Scott Guthrie</Name>
<Title>General Manager</Title>
<Email>scottgu@microsoft.com</Email>
<Age>36</Age>
<YearAtCompany>10</YearAtCompany>
</Contact>
<Contact>
<Name>Bill Gates</Name>
<Title>Chairman</Title>
<Email>billgates@microsoft.com</Email>
<Age>50</Age>
</Contact>
</Contacts>
<Contacts>
<Contact>
<Name>Scott Guthrie</Name>
<Title>General Manager</Title>
<Email>scottgu@microsoft.com</Email>
<Age>36</Age>
<YearAtCompany>10</YearAtCompany>
</Contact>
<Contact>
<Name>Bill Gates</Name>
<Title>Chairman</Title>
<Email>billgates@microsoft.com</Email>
<Age>50</Age>
</Contact>
</Contacts>
??操作符在VS2005下不支持的.