我有一个名为 Sample 的类,其中有一个名为 Name 的字符串属性,覆盖 ToString() 以返回 Name 属性。
然后我创建了两个实例 s1 和 s2,s1 已初始化,它的 Name 属性设置为“ABC”,s2 设置为 null。
当我尝试使用 ?? 打印值时c# 的运算符,s2 不打印值字符串“Null”。
class Program
{
static void Main(string[] args)
{
Sample s1 = new Sample();
s1.Name = "ABC";
Sample s2 = null;
Console.WriteLine("Some Sample Name : " + s1 ?? "Null");
Console.WriteLine("Some Sample Name : " + s2 ?? "Null");
Console.ReadLine();
}
}
class Sample
{
string _Name;
public string Name
{
get { return _Name; }
set { _Name = value; }
}
public override string ToString()
{
return Name;
}
}
输出:
Some Sample Name : ABC
Some Sample Name :
最佳答案
这是一个 operator precedence问题,您的代码首先执行 +
,将 "Some Sample Name : "
文字与 s1
组合,然后应用 ??
到此。
由于 s1
和 s2
是 Sample
,而不是 String
,因此您不能使用 s1 ?? “空”
。可能最简单的事情是使用条件运算符:
Console.WriteLine("Some Sample Name : " + (s1 == null ? "Null" : s1.ToString()));
关于C# ??如果变量为空,运算符不打印值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25637261/