为什么不能将可为null的int隐式转换为int?技术原因还是设计选择? [英] Why can't a nullable int be implicitly conversion to an int ? Technical reason or design choice?
问题描述
在C#中,没有从 int?
类型隐式转换为 int
类型.
In C#, there is no implicit conversion from the int?
type to the int
type.
我已经定义了以下隐式运算符
I have defined the following implicit operator
namespace System
{
public partial struct Int32
{
public static implicit operator Int32(int? v)
{
return (Int32)(v ?? 0);
}
}
}
这允许我编译以下代码
int? nullableInt = 0;
Int32 regularInt = nullableInt;
但是如果我将 regularInt
定义为 int
而不是 Int32
,则会出现以下错误
but if I define regularInt
as an int
instead of Int32
I get the following error
无法隐式转换类型'int?'到"int".存在显式转换(您是否缺少演员表?)
Cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you missing a cast?)
我希望 int
和 Int32
是可互换的,但显然并不是在构建C#语言时就考虑了此功能.
I expected int
and Int32
to be interchangeable but the C# language clearly hasn't been built with this functionality in mind.
无法定义此操作背后是否有技术原因,是否已做出决定以防止潜在的代码气味?
Is there a technical reason behind the impossibility of defining this operation, is it a decision made to prevent potential code smell ?
我知道定义这样的隐式运算符可能会导致某些非常意外的行为,因为从 null
值到 0
整数的转换不会在任何情况下都有意义.这个问题更多的是关于为什么不能做到"而不是为什么做这是一个真的坏主意"
I'm aware that defining such an implicit operator could result in some very unexpected behavior, as the conversion from a null
value to a 0
integer doesn't make sense in every situation. This question is more about "why can't it be done" than "why doing it is a really bad idea"
推荐答案
您所拥有的代码没有添加从.NET的可为null的int到.NET的int的隐式转换.它在 System
名称空间中创建了一个称为 Int32
的全新类型,但是由于它与Core.dll位于不同的程序集中,因此它是另一种类型.(看看 typeof(int).FullName
和 typeof(int32).FullName
可以看到这一点.)
The code you have doesn't add an implicit conversion from the .NET's nullable int to .NET's int. It creates a whole new type, called Int32
, in the System
namespace, but as it's in a different assembly than Core.dll, it's a different type. (Take a look at typeof(int).FullName
and typeof(int32).FullName
to see this.)
设置了您展示的用于测试此隐式转换的代码,以使其尝试将系统的可为null的类型转换为您自己的新类型,并且由于创建了这种隐式转换,因此成功.当您使用系统类型而不是您自己的新类型时,它会失败,因为这些类型之间没有隐式转换.
The code you showed to try to test this implicit conversion is set up so that it's trying to convert the system's nullable type to your own new type, and since you created such an implicit conversion, it succeeds. It fails when you use the system type instead of your own new type because there is no implicit conversion between those types.
您不能从这些类型之一的定义之外为类型创建隐式(或显式)转换,并且由于您无法访问 Nullable
或.NET Int32的源,因此您无法添加隐式转换.
You cannot create implicit (or explicit) conversions for types from outside the definition of one of those types, and since you can't access the source of either Nullable
or the .NET Int32, you can't add an implicit conversion.
这篇关于为什么不能将可为null的int隐式转换为int?技术原因还是设计选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!