问题描述
我有一个结构(出于这个问题的目的)非常类似于内置的 Point
类型.
I have a struct that (for the purposes of this question) pretty much mimics the built in Point
type.
在使用它之前,我需要检查它是否已实例化.当它是 Point
时,我可以这样做:
I need to check that it has been instantiated before using it. When it was Point
, I could do this:
if (this.p == null)
但是现在会产生以下错误:
But that now generates the following error:
如何比较我的struct和null?还有另一种检查实例化的方法吗?
How can I compare my struct against null? Is there another way to check for instantiation?
推荐答案
struct
是一种值类型-永远不会为空.
A struct
is a value type - it's never null.
您可以检查 default(ProportionPoint)
,它是结构的默认值(例如零).但是,有一点可能是默认值-原点-也是有效"值.
You can check against default(ProportionPoint)
, which is the default value of the struct (e.g. zero). However, for a point, it may be that the default value - the origin - is also a "valid" value.
相反,您可以使用 Nullable< ProportionPoint>
.
这篇关于如何检查结构是否已实例化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!