double? test = true ? null : 1.0;
Run Code Online (Sandbox Code Playgroud)
在我的书中,这是一样的
if (true) {
test = null;
} else {
test = 1.0;
}
Run Code Online (Sandbox Code Playgroud)
但是第一行给出了这个编译错误:
无法确定条件表达式的类型,因为'
<null>'和'double' 之间没有隐式转换.
我正在尝试使用条件运算符,但我会挂起它认为结果应该是的类型.
下面是一个我设法表明我遇到的问题的例子:
class Program
{
public static void OutputDateTime(DateTime? datetime)
{
Console.WriteLine(datetime);
}
public static bool IsDateTimeHappy(DateTime datetime)
{
if (DateTime.Compare(datetime, DateTime.Parse("1/1")) == 0)
return true;
return false;
}
static void Main(string[] args)
{
DateTime myDateTime = DateTime.Now;
OutputDateTime(IsDateTimeHappy(myDateTime) ? null : myDateTime);
Console.ReadLine(); ^
} |
} |
// This line has the compile issue ---------------+
Run Code Online (Sandbox Code Playgroud)
在上面指出的行上,我得到以下编译错误:
无法确定条件表达式的类型,因为'<null>'和'System.DateTime'之间没有隐式转换
我很困惑因为参数是可以为空的类型(DateTime?).为什么需要转换呢?如果它为null,则使用它,如果是日期时间则使用它.
我的印象是:
condition ? first_expression : second_expression;
Run Code Online (Sandbox Code Playgroud)
与以下相同:
if (condition)
first_expression;
else
second_expression;
Run Code Online (Sandbox Code Playgroud)
显然情况并非如此.这背后的原因是什么?
(注意:我知道,如果我将"myDateTime"设为可以为空的DateTime,那么它会起作用.但为什么需要呢?
正如我之前所说,这是一个人为的例子.在我的实例中,"myDateTime"是一个数据映射值,不能为空.)
c# nullable ternary-operator type-conversion conditional-operator
比如我已宣布,
双x;
现在我想分配
x = NULL我该怎么办?我已经看到了其他一些答案,但无法理解它们,这就是打开这个主题的原因.
这将无法编译,说明"无法确定条件表达式的类型,因为'System.DateTime'和''"之间没有隐式转换
task.ActualEndDate = TextBoxActualEndDate.Text != "" ? DateTime.Parse(TextBoxActualEndDate.Text) : null;
Run Code Online (Sandbox Code Playgroud)
这很好用
if (TextBoxActualEndDate.Text != "")
task.ActualEndDate = DateTime.Parse(TextBoxActualEndDate.Text);
else
task.ActualEndDate = null;
Run Code Online (Sandbox Code Playgroud) 我试图弄清楚为什么在以下示例中需要强制转换:
bool test = new Random().NextDouble() >= 0.5;
short val = 5;
// Ex 1 - must cast 0 to short
short res = test ? 5 : 0; // fine
short res = test ? val : 0; // error
short res = test ? val : (short)0; // ugly
// Ex 2 - must cast either short or null to short?
short? nres = test ? val : null; // error
short? nres = test ? (short?)val : …Run Code Online (Sandbox Code Playgroud) 我想检查DateTime变量"starttime"和"endtime"有null值,然后试图初始化到empty如下的价值,但我运行到下面的编译错误.实现这一目标的最佳方法是什么?
string htmllink = "";
DateTime? starttime = null;
DateTime? endtime = null;
htmllink = (dbNullCheck.isColumnNull(rdr, "html_link")) ? "" : rdr.GetString(3);
starttime = (dbNullCheck.isColumnNull(rdr, "start_time")) ? "" : rdr.GetString(4);
endtime = (dbNullCheck.isColumnNull(rdr, "end_time")) ? "" : rdr.GetString(5);
results.htmllist.Add(new gethtmllist() { resulthtmllink = htmllink,
duration = (starttime - endtime).ToString() });
Run Code Online (Sandbox Code Playgroud)
错误:
错误2无法将类型'string'隐式转换为'System.DateTime?'
更新: -
string htmllink = "";
htmllink = (dbNullCheck.isColumnNull(rdr, "html_link")) ? "" : rdr.GetString(3);
DateTime? starttime = (dbNullCheck.isColumnNull(rdr, "start_time")) …Run Code Online (Sandbox Code Playgroud) 假设两个类,都是同一个超类的后代,如下所示:
class MySuperClass{}
class A : MySuperClass{}
class B : MySuperClass{}
Run Code Online (Sandbox Code Playgroud)
然后这个赋值不会通过编译器:
MySuperClass p = myCondition ? new A() : new B();
Run Code Online (Sandbox Code Playgroud)
编译器抱怨A和B不兼容(无法确定条件表达式的类型,因为'A'和'B'之间没有隐式转换 [CS0173]).但它们都是MySuperClass类型,所以在我看来这应该有效.不是说这是一个大问题; 只需要一个简单的强制转换即可启发编译器.但肯定是C#编译器的一个障碍?你不同意吗?
我刚刚遇到这个(编写代码来演示"问题"):
public ICollection<string> CreateCollection(int x)
{
ICollection<string> collection = x == 0
? new List<string>()
: new LinkedList<string>();
return collection;
}
Run Code Online (Sandbox Code Playgroud)
编译器抱怨:
Fehler CS0173:Der Typ des bedingten Ausdrucks kann nicht bestimmt werden,weil keine implizite Konvertierung zwischen"System.Collections.Generic.List"und"System.Collections.Generic.LinkedList"erfolgt.
其翻译大致为:
无法确定条件运算符的类型,因为List和LinkedList之间没有隐式转换.
我可以看到为什么编译器抱怨,但是,嘿,来吧.它试图发挥愚蠢.我可以看到两个表达式不是同一类型,而是有一个共同的祖先,作为奖励,左侧的类型也是共同的祖先.我相信编译器也可以看到它.如果左侧被声明为,我可以理解错误var.
我在这里错过了什么?
编辑:
我接受詹姆斯·冈特的解释.也许只是为了说清楚.我可以很好地阅读编译器规范.我想了解原因.为什么有人决定以这种方式编写规范.这种设计背后必然有一个原因.根据詹姆斯的说法,设计原则是"毫无意外".此外,CodeInChaos还解释了如果编译器试图从常见的祖先中推断出类型,您可能遇到的惊喜.
var dict = new Dictionary<string, object>();
DateTime? myDate;
/*Next line gives: Type of conditional expression cannot be
determined because there is no implicit conversion between 'System.DateTime?'
and 'System.DBNull' */
dict.Add("breakit", myDate.HasValue ? myDate.Value : DBNull.Value);
Run Code Online (Sandbox Code Playgroud)
我不明白为什么如果一个或另一个进入期望类型为Object的字典,则需要进行隐式转换.
我有一个功能,可以回放一个可空的struct.我注意到两个类似的案例
第一:效果很好:
public static GeometricCircle? CircleBySize(GeometricPoint point, double size)
{
if (size >= epsilon)
return null;
return new GeometricCircle(point.Position, new Vector(1, 0, 0), size, true);
}
Run Code Online (Sandbox Code Playgroud)
第二:需要将null值转换为GeometricCircle吗?
public static GeometricCircle? CircleBySize(GeometricPoint point, double size)
{
return size > epsilon ? new GeometricCircle(point.Position, new Vector(1, 0, 0), size, true) : (GeometricCircle?)null;
}
Run Code Online (Sandbox Code Playgroud)
有人知道有什么区别吗?