Domanda

I have a Coordinates class which is defined below:

public class Coordinates
{
    [XmlIgnore]
    public Vector3 Vector3 { get { return new Vector3(X, Y, Z); } set { X = value.X; Y = value.Y; Z = value.Z; } }

    [XmlIgnore]
    public Coordinates(float cX, float cY, float cZ) { X = cX; Y = cY; Z = cZ; }

    [XmlIgnore]
    public Coordinates(Vector3 coord) { X = coord.X; Y = coord.Y; Z = coord.Z; }

    public float X { get; set; }
    public float Y { get; set; }
    public float Z { get; set; }
}

I need to be able to define a new instance of this class using these 3 ways:

Coordinates var = new Coordinates(1,2,3);
Coordinates var = new Coordinates(Vector3.Zero);
Coordinates var = new Coordinates { X = 0, Y = 0, Z = 0 }

The first two work, but the third one doesn't. If I remove the constructors from my class, the third one works but not the two first ones.

How do I get this working?

È stato utile?

Soluzione

This is because when you do not have any constructor defined, the compiler inserts a default constructor with no arguments. You just need to add an empty constructor,

public Coordinates() { } 

and then you can use all three versions

Altri suggerimenti

If you add a constructor the default constructor is omitted.

Just add this code to your class:

public Coordinates()
{
}

The third one is just a shorter form (syntax sugar) for the following code:

Coordinates var = new Coordinates();
var.X = 0;
var.Y = 0;
var.Z = 0;

Therefore you need a parameterless, default constructor; which was generated by the compiler when no constructor was defined. Be aware that in that case the caller is not required to set the value of the public attributes X, Y and Z.

The third one is a default constructor, the default constructor is only publicly available if there are no other constructors defined.

To state that you also wish to make the default constructor public again you need to explicitly state so.

public Coordinates() { }

You are missing a default constructor which, when you don't have any constructors at all is generated automatically. Add the line:

public Coordinates(){}

You need to use a blank constructor and call it, you cannot create a new object without calling one. A default and parameterless constructor is automatically made when no others are defined, but after creating your own other constructors, you must provide a default one in order to use that syntax.

Add this to your Coordinates class:

public Coordinates()
{
}

And create the object like this:

Coordinates var = new Coordinates() { X = 0, Y = 0, Z = 0 };

That is because you do not have a default constructor defined in your class. All that you need to do is to add one like this:

public Coordinates()
{
}

Another way is to use the one with the three float variables like this:

Coordinates coords = new Coordinates(cX: 0, cY: 0, cZ: 0);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top