为什么结构在vb和c#中表现不同? [英] Why structure behaves differently in vb and c#?
本文介绍了为什么结构在vb和c#中表现不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
结构是一个值类型,不能有空值,那么为什么它在vb和c#中表现不同?
structure is a value type and can't have null values then why it behaves different in vb and c#?
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim c As System.Drawing.Color
If c <> Nothing Then
MessageBox.Show(c.Name)
Else
MessageBox.Show("null")
End If
End Sub
Public Enum Align
Left
Center
Right
End Enum
Public Alignment As Align
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
If Alignment <> Nothing Then
MessageBox.Show("true")
Else
MessageBox.Show("false")
End If
End Sub
private void button1_Click(object sender, EventArgs e)
{
System.Drawing.Color c = default(System.Drawing.Color);
if (c != null)
{
MessageBox.Show(c.Name);
}
else
{
MessageBox.Show("null");
}
}
public enum Align
{
Left,
Center,
Right
}
public Align Alignment;
private void button2_Click(object sender, EventArgs e)
{
if (Alignment != null)
{
MessageBox.Show("true");
}
else
{
MessageBox.Show("false");
}
}
推荐答案
为什么结构在vb和c#中表现不同?
它没有。您在代码中看到的是C#中null
与VB.NET中Nothing
之间的区别。 />
null
是非参考,仅限于此。结构和枚举是值类型,而不是引用类型,因此您不能为它们指定null。
Nothing
是您分配给它的任何内容的默认值。对于引用类型,它与null
相同。对于值类型,它是它们的默认值,因此通常为0。结构和枚举具有默认值,因此您可以为它们分配Nothing
。
所以,VB.NET中没有
基本上是null
和默认(T)
C#中的一个。
Why structure behaves differently in vb and c#?
It doesn't. What you're seeing in your code is the difference betweennull
in C# andNothing
in VB.NET.
null
is a non-reference and only that. Structures and Enums are value types, not reference types, so you can't assign null to them.
Nothing
is the default value of whatever you assign it to. For reference types, it's the same asnull
. For value types, it's their default value, so 0 in general. Structures and Enums have a default value, so you can assignNothing
to them.
So,Nothing
in VB.NET is basically thenull
anddefault(T)
of C# in one.
这篇关于为什么结构在vb和c#中表现不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文