English 中文(简体)
为什么可替代的<T>被认为是一种价值类型?
原标题:Why are Nullable<T> considered a value type?

您是否曾尝试使用<代码>Convert.ChangeType()方法将价值转换为Nullable<T>类型? 反之,它将推出<条码>InvalidCastException,指出“不可将Null物体转换为一种价值类型”。

紧靠你的窗户:?System.Convert.ChangeType(null,打字)

出于某种模糊的原因,可替代物被视为价值类型。 例如,typeof(int?) IsValueType Returntrue

对于我来说,由于<代码>Nullable<T>接受null<>/code>,它具有一个类别,而不是一个价值类别。 是否有任何人知道为什么会区别对待?

最佳回答

<代码>System.Nullable<T>在技术上是一个结构,因此具有价值类型(null)。 <代码>Nullable<T>的数值与无效参考值并不完全相同。 它是一只大旗,表示缺乏价值。 然而,它特别按操作时间处理,因此是一种宽价。 首先,它没有达到<代码>,在T : 结构。 类型限制(t 满足,T :, 或者,对于其价值而言。 其次,它显示了一种有趣的箱子行为。 插文如下:

  • A null reference, if the value is null.
  • 如果实际含有一定价值,则底型的箱值。 这就是说:

    int? x = 2;
    object y = x;
    

    <代码>y并不是一个箱子:Nullable<int>。 它只是一个盒式的<代码>int。 您可以找到<代码>T至Nullable<T>(当然还有)。 <代码>null reference to Nullable<T> results in a null Value (如你预计)。

操作时间的这种特殊处理使得可取消的类型的工作更加类似于参考类型中的<代码>null。

问题回答

,但从null无价值()。 HasValue = 虚假。 还有一种从类型<代码>T到类型Nullable<T>的数值的默示换算。

此外,所有运营商都从正常类型上取消,以直接从事无损的工作。

我刚刚在的“相关问题”名单上看到这个问题。 为什么是不可磨灭的; T> is a ruct?,我认为我的答复也在此适用。 <代码>Nullable<T>的全点是,除能够得出无效价值外,在每一方面均采用同样的价值类型。

可以用两种方式看待无效。 一种是,它指任何东西,另一种是它没有有意义的价值。 总的来说,这两种不同的表述方式是相同的,但它们有不同的用途。

Nullable<T> > 让我们能够说“这没有任何有意义的价值”,并在某种程度上,它可以有相同的语义,作为无效的参考,但并不喜欢以任何其他方式提及。 如果无效,“无有意义的价值”就完全无效,而不是“无意义”是指任何东西,如果无效,则具有价值,而不是提及。

(Aaronatt 认为,这意味着不可赔偿实际上可以包含无效,而我不同意,因为在其使用时,他的观点是,即使“null”一词与提及不同,我们实际上的分歧是一个我们选择使用的那种抽象的问题。)

<代码>Nullable<T>作为指示和构件加以实施是价值类型。





相关问题
Manually implementing high performance algorithms in .NET

As a learning experience I recently tried implementing Quicksort with 3 way partitioning in C#. Apart from needing to add an extra range check on the left/right variables before the recursive call, ...

Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

How do I compare two decimals to 10 decimal places?

I m using decimal type (.net), and I want to see if two numbers are equal. But I only want to be accurate to 10 decimal places. For example take these three numbers. I want them all to be equal. 0....

Exception practices when creating a SynchronizationContext?

I m creating an STA version of the SynchronizationContext for use in Windows Workflow 4.0. I m wondering what to do about exceptions when Post-ing callbacks. The SynchronizationContext can be used ...

Show running instance in single instance application

I am building an application with C#. I managed to turn this into a single instance application by checking if the same process is already running. Process[] pname = Process.GetProcessesByName("...

How to combine DataTrigger and EventTrigger?

NOTE I have asked the related question (with an accepted answer): How to combine DataTrigger and Trigger? I think I need to combine an EventTrigger and a DataTrigger to achieve what I m after: when ...

热门标签