Tag: 可空的

C#ADO.NET:nulls和DbNull – 有更有效的语法吗?

我有一个DateTime? 我试图插入到使用DbParameter字段。 我正在创build这样的参数: DbParameter datePrm = updateStmt.CreateParameter(); datePrm.ParameterName = "@change_date"; 然后我想把DateTime?的值DateTime? 进入dataPrm.Value同时占null 。 我以为我会很聪明: datePrm.Value = nullableDate ?? DBNull.Value; 但失败的错误 运营商“??” 不能应用于“System.DateTime?”types的操作数 和“System.DBNull” 所以我猜想,只有第二个参数是第一个参数的非空值版本才有效。 那么我去了: datePrm.Value = nullableDate.HasValue ? nullableDate.Value : DBNull.Value; 但是这也不起作用: 条件expression式的types不能确定,因为没有“System.DateTime”和“System.DBNull”之间的隐式转换 但我不想在这些types之间转换! 到目前为止,我唯一可以工作的是: if (nullableDate.HasValue) datePrm.Value = nullableDate.Value; else datePrm.Value = DBNull.Value; 那真的是我写这个的唯一方法吗? 有没有办法使用三元运算符来实现单线程工作? 更新:我真的不明白为什么? 版本不起作用。 MSDN说: ?? 如果操作数不为null,则返回左操作数,否则返回右操作数。 这正是我想要的! Update2:最后这是很明显的: datePrm.Value […]

严重的错误与int提升/可空转换,允许从十进制转换

我认为这个问题会使我立即在Stack Overflow上成名。 假设你有以下types: // represents a decimal number with at most two decimal places after the period struct NumberFixedPoint2 { decimal number; // an integer has no fractional part; can convert to this type public static implicit operator NumberFixedPoint2(int integer) { return new NumberFixedPoint2 { number = integer }; } // this type is a […]

PHP7中可为空的返回types

PHP 7引入了返回types声明 。 这意味着我现在可以指示返回值是一个特定的类,接口,数组,可调用的或新的可标注的标量types之一,这对于函数参数是可能的。 function returnHello(): string { return 'hello'; } 通常情况下,一个值并不总是存在的,你可能会返回某种types的值,或者返回null。 虽然可以通过将参数的默认值设置为null( DateTime $time = null )来使参数为空,但是对于返回types似乎没有办法做到这一点。 确实如此,或者我不知道如何去做? 这些不起作用: function returnHello(): string? { return 'hello'; } function returnHello(): string|null { return 'hello'; }

可为空的对象必须有一个值

exception描述中有一个悖论:可为空的对象必须有一个值(?!) 这就是问题: 我有一个DateTimeExtended类,有 { DateTime? MyDataTime; int? otherdata; } 和一个构造函数 DateTimeExtended(DateTimeExtended myNewDT) { this.MyDateTime = myNewDT.MyDateTime.Value; this.otherdata = myNewDT.otherdata; } 运行这个代码 DateTimeExtended res = new DateTimeExtended(oldDTE); 抛出一个InvalidOperationException与消息: 可为空的对象必须有一个值。 myNewDT.MyDateTime.Value – 有效且包含常规的DateTime对象。 这条信息的意思是什么,我做错了什么? 请注意, oldDTE不为null 。 我已经从myNewDT.MyDateTime删除了Value ,但是由于生成的setter会引发同样的exception。

可空types不是可空types?

我正在做一些可空types的testing,并没有像我预期的那样工作: int? testInt = 0; Type nullableType = typeof(int?); Assert.AreEqual(nullableType, testInt.GetType()); // not the same type 这也不起作用: DateTime? test = new DateTime(434523452345); Assert.IsTrue(test.GetType() == typeof(Nullable)); //FAIL DateTime? test = new DateTime(434523452345); Assert.IsTrue(test.GetType() == typeof(Nullable<>)); //STILL FAIL 我的问题是为什么testInt.GetType()返回int,并且typeof(int?)返回true的可空types?