相关疑难解决方法(0)

为什么这个C#代码没有编译?

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' 之间没有隐式转换.

.net c# nullable

11
推荐指数
2
解决办法
2186
查看次数

在C#中使用条件运算符键入结果

我正在尝试使用条件运算符,但我会挂起它认为结果应该是的类型.

下面是一个我设法表明我遇到的问题的例子:

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

11
推荐指数
1
解决办法
1126
查看次数

如何在C#中将Null值赋给Non-Nullable类型变量?

比如我已宣布,

双x;

现在我想分配

x = NULL我该怎么办?我已经看到了其他一些答案,但无法理解它们,这就是打开这个主题的原因.

c#

10
推荐指数
2
解决办法
3万
查看次数

为什么条件运算符没有正确地允许使用"null"来赋值为可空类型?

可能的重复:
可空类型和三元运算符.为什么这不起作用?
具有可空<value>类型的条件运算符赋值?

这将无法编译,说明"无法确定条件表达式的类型,因为'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)

.net c# nullable conditional-operator

8
推荐指数
1
解决办法
4140
查看次数

使用C#三元条件运算符进行必需的转换

我试图弄清楚为什么在以下示例中需要强制转换:

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)

c# casting ternary-operator

7
推荐指数
1
解决办法
1012
查看次数

如何将空值初始化为datetime变量?

我想检查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)

c# asp.net

6
推荐指数
1
解决办法
3229
查看次数

条件运算符会混淆,但为什么呢?

假设两个类,都是同一个超类的后代,如下所示:

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#编译器的一个障碍?你不同意吗?

c# compiler-construction inheritance

5
推荐指数
1
解决办法
673
查看次数

无法确定条件表达式的类型?

我刚刚遇到这个(编写代码来演示"问题"):

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还解释了如果编译器试图从常见的祖先中推断出类型,您可能遇到的惊喜.

.net c# compiler-construction

5
推荐指数
1
解决办法
2674
查看次数

为什么我不能使用这个表达式的三元运算符?

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的字典,则需要进行隐式转换.

c# ternary-operator implicit-conversion

5
推荐指数
1
解决办法
3388
查看次数

为什么要将null值转换为可以为null的struct

我有一个功能,可以回放一个可空的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)

有人知道有什么区别吗?

c# nullable type-conversion

3
推荐指数
1
解决办法
251
查看次数