我们可以将空值分配给结构类型的变量吗?
struct MyStruct
{
}
MyStruct var = null;
这在C# .net中是否可能?
如果不是? 那么,C#如何允许Nullable <T >可被分配为无效的固定变量类型?
我们可以将空值分配给结构类型的变量吗?
struct MyStruct
{
}
MyStruct var = null;
这在C# .net中是否可能?
如果不是? 那么,C#如何允许Nullable <T >可被分配为无效的固定变量类型?
关于:
C#如何允许可以将Nullable<T>结构类型的变量赋为null?
答案实际上非常简单: C#汇编者知道Nullable<T>
,并将其作为维持幻觉的特殊案例处理。
例如,这个:
int? a;
if (a != null) ...
实际上编译成这个:
if (a.HasValue) ...
几乎所有的这种魔法都由编译器处理——.NET主要将Nullable<T>
视为另一种ValueType。我记得读过(很可能是来自Eric Lippert的博客), 在开发过程的后期,他们发现了一个特殊问题,仅靠编译器技巧无法解决。运行时的人同意做出一个改变,将Nullable<T>
视为一个特殊情况。不幸的是,我不记得特殊情况是什么了,也找不到参考文献了。
Please review this article for details (especially the second comment which is by Lippert): http://blogs.msdn.com/ericlippert/archive/2008/05/07/covariance-and-contravariance-part-twelve-to-infinity-but-not-beyond.aspx
是的,这是可能的,但你必须将你的变量声明为可为空的:
MyStruct? foo = null;
或者 (huò zhě)
Nullable<MyStruct> foo = null;
在C#中, struct
是值类型,而 class
是引用类型。
结构体无法变成null,因此您必须使用Nullable
这可以通过在声明中直接使用Nullable<T>
类来完成:
Nullable<MyStruct> foo;
或者使用Nullable<T>
的语法糖:
MyStruct? foo;
结构体不能为 null,可空类型 用于创建可空结构体的实例。
Asiento ******** Id_Asiento integer key Fecha date It_Asiento ********** Id_Asiento integer Forenkey Importe float I wan to do This SQL Query with Linq select Asiento.Id_Asiento, ...
I have code listed here: Threading and Sockets. The answer to that question was to modify isListening with volatile. As I remarked, that modifier allowed me to access the variable from another thread....
Is their a way in c# to instantiate a variable into a method call without using a switch statement.
Saw the code here. Can any one tell me what it means? Action wrappedAction = () => { threadToKill = Thread.CurrentThread; action(); }; Can we write such code with ...
I m sure this is simple but it s driving me nuts. I have a ListBox on my page to show artists, which calls a method when the index is changed, and a button which loads an artist from that list in ...
How to cancel an asynchronous call? The .NET APM doesn t seem to support this operation. I have the following loop in my code which spawns multiple threads on the ThreadPool. When I click a button on ...
I have a section of code that looks like this: try { classVar = functionCall(input, sEnum.First); classVar = functionCall(input, sEnum.Second); classVar = functionCall(input, sEnum.Third); } ...
I have done my project and now it is documentation time. Up to now I was able to generate the XML files from the project. Now I want to get the HTML API out of it. But I can t figure it out.