When defining a struct similar to System.Drawing.Point but with double instead of float: How to use X and Y without assigning a value to them first?

Example:

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;
}
有帮助吗?

解决方案

You are mistaken. The code you talked about woks just fine and there is no difference between PointF and your 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;
    }

The title of form1 shows "00" as expected.

Edit:

Maybe you are wondering why you get a complier error when you try to use a struct directly, that was not created but do not get an error when you use an un-created struct within a struct. Or one within a struct within a struct within a struct within a struct..

Which should make it clear: The compiler doesn't follow these levels of nesting; it just flags things that are obvious to it, that is omissions within its direct scope.

Granted, this can be a nuisance but all in all I'm glad to be warned instead of being allowed to forget initialization.

其他提示

It looks like you know System.Drawing.Point (and probably System.Drawing.PointF), but, like I did the first time I needed to use those classes, you desired to have identical functionality BUT with double instead of int (or float).

Well, then I discovered System.Windows.Point, which uses double and works pretty much the same way, except it is defined in other .NET assembly (you need to add other reference).

By the way, there are also the very useful structs System.Windows.Vector, System.Windows.Media.Media3D.Point3D and System.Windows.Media.Media3D.Vector3D. These include native vector arithmetics (you add a Vector to a Point and get another Point, you add two Vectors and get a new Vector, etc.) and the often-asked-for DotProduct and CrossProduct.

(The struct System.Windows.Point was mentioned in a comment but in such a "tangential" way considering the OP explicit need, that I found it deserved its own answer).

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top