c# null for System.drawing.PointT

标签 c# nullable system.drawing

我将 C# 用于图形。现在我想为 PointF 返回一个 null

    /// <summary>
    /// Project the point according to camera position.
    /// </summary>
    /// <param name="p">Point position, in WC</param>
    /// <returns>pixel position</returns>
    public PointF Project(MCvPoint3D32f p)
    {
        //return new PointF(p.x, p.y);
        // Extend p
        Matrix<double> p_ex = new Matrix<double>(3, 1);
        p_ex[0, 0] = p.x;
        p_ex[1, 0] = p.y;
        p_ex[2, 0] = p.z;

        var rst = HomographMatrix * p_ex;
        rst[0, 0] = rst[0,0] / rst[2, 0] * focalLength * scale;
        rst[1, 0] = rst[1, 0] / rst[2, 0] * focalLength * scale;

        return new PointF((float)rst[0, 0], (float)rst[1, 0]);
    }

在这里,如果点不在我的相机的 FoV 范围内,我想为该点返回一个“null”。但实际上 PointF 不是“可空”的,那么是否有直接的方法为该点返回“空”?

不想继承原生的PointF

最佳答案

在某些方面,这取决于您的要求。例如,如果您需要存储很多点(因此空间是一个因素),您可以使用某种标记值 - 也许:

static readonly PointF NilPoint = new PointF(float.NaN, float.NaN);

然后检查该运行时,可能使用辅助方法:

public static bool IsNil(this PointF value)
{
    return float.IsNaN(value.X) || float.IsNaN(value.Y);
}

所以你可以检查:

if(!point.IsNil()) {
    // etc   
}

然而,一个更简单的选择(有轻微的空间开销)就是使用 Nullable<T> ,即

PointF? pt1 = null; // fine
PointF? pt2 = new PointF(123,456); // also fine

关于c# null for System.drawing.PointT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16891348/

相关文章:

c# - 将 Nullable 转换为 ValueType

c# - 将 Simpleitk 图像转换为位图。系统参数异常

c# - IE 7 错误? - 下载文件时提示保存/打开 - c# asp.net 3.5

intellij-idea - 我可以通过 Java API 对平台类型强制实现空安全吗?

c# - UserControl 属性的默认值

c# - 为什么 null 传播不一致地传播 Nullable<T>?

c# - 在透明像素上使用 DrawString 呈现错误的文本

c# - System.Drawing 对象非托管资源处理

c# - 如何从两个数组中过滤相同的字符串并只显示一次

c# - 使用 LinQ 合并 2 个不同类型的列表