0

如果值类型被声明为可为空,我应该如何采取预防措施?即如果在构造函数中我有:

public Point3 ( Point3 source )
{
    this.X = source.X;
    this.Y = source.Y;
    this.Z = source.Z;
}

如果源为空,它会失败吗?

4

5 回答 5

10

如果它是一种值类型,我看不到存在的可能性Point3null你不会错过一个问号吗?如果你真的是说Point3?,那么你应该像这样访问它:

public Point3 ( Point3? source )
{
    this.X = source.Value.X;
    this.Y = source.Value.Y;
    this.Z = source.Value.Z;
}

在这种情况下,如果Value属性是null.

于 2009-06-01T20:26:38.203 回答
3

此方法的调用者将无法传入可空点,因为该方法采用常规点,而不是可空点。因此,您无需担心 Point 在构造函数代码中为空。

于 2009-06-01T20:28:30.913 回答
2

source是的,如果为空,那将失败。

source如果为空,您必须决定正确的行为应该是什么。你可能只是抛出一个异常。

public Point3 ( Point3? source )
{
    if (source == null) 
    {
        throw new ArgumentNullException("source");
    }

    this.X = source.Value.X;
    this.Y = source.Value.Y;
    this.Z = source.Value.Z;
}

或者,如果您不想接受null的值source,只需保留示例中的方法即可。该方法不接受 a Nullable<Point3>,因此在这种情况下您不必担心它null

于 2009-06-01T20:28:06.670 回答
1
    public Point3(Point3? source) { 
       this.X = source.GetValueOrDefault().X; 
        this.Y = source.GetValueOrDefault().Y;
        this.Z = source.GetValueOrDefault().Z; 
    }
于 2009-06-01T20:54:59.613 回答
1

如果source是 aPoint3?就不会是 a 了Point3。据我所知,它会在编译时失败。要发送 aPoint3?你必须使用.Value,如果它为空,我相信它会引发异常。

于 2009-06-01T20:29:25.110 回答