如何使用结构体的字段而不首先为其赋值

本文关键字:赋值 何使用 结构体 字段 | 更新日期: 2023-09-27 18:01:31

当定义一个类似于System.Drawing.Point的结构体时,但用double代替float:如何使用X和Y而不首先给它们赋值?

的例子:

public struct PointD
{
    public double X;
    public double Y;
}
static void Main()
{
    PointD testPointD;
    double d = testPointD.X; // CS0170: Use of possibly unassigned field 'X'
    
    
    System.Drawing.Point point;
    // Here I can use X without defining it first.
    // So I guess the struct is doing something to make that work?
    // Edit: This also doesn't work, but Visual Studio did not underline it,
    // my fault!
    int i = point.X;
}

如何使用结构体的字段而不首先为其赋值

你错了。你说的代码工作得很好,PointF和PointD:

没有区别
    public Form1()
    {
        InitializeComponent();
        MyStruct ms = new MyStruct();
        this.Text = ms.p.X.ToString() + ms.d.X.ToString();
    }
    public struct PointD
    {
        public double X;
        public double Y;
    }
    public struct MyStruct
    {
        public PointF p;
        public PointD d;
    }

form1的标题如预期显示"00"

编辑:

也许你想知道为什么当你试图直接使用一个结构时,你会得到一个编译器错误,这是没有创建的,但当你在一个结构中使用一个未创建的结构时,不会得到一个错误。或者结构中的结构中的结构中的结构中的结构。

应该清楚地表明:编译器不遵循这些嵌套级别;它只标记对它来说很明显的东西,也就是它直接作用域内的遗漏。

当然,这可能是一个麻烦,但总的来说,我很高兴得到警告,而不是被允许忘记初始化。

看起来你知道System.Drawing.Point(也可能是System.Drawing.PointF),但是,就像我第一次需要使用这些类一样,你希望具有相同的功能,但是使用double而不是int(或float)。

嗯,然后我发现了System.Windows.Point,它使用double,工作方式几乎相同,除了它是在其他。net程序集中定义的(你需要添加其他引用)。

顺便说一下,还有非常有用的结构体System.Windows.Vector, System.Windows.Media.Media3D.Point3DSystem.Windows.Media.Media3D.Vector3D。这些包括原生向量算法(将一个向量添加到一个点并得到另一个点,将两个向量添加并得到一个新向量,等等)以及经常被要求的点积和叉积。

(struct System.Windows.Point在评论中提到过,但考虑到OP显式的需要,这种"切题"的方式,我觉得它应该有自己的答案)。