Domanda

i have looked around quite a bit and i understand how to overload a constructor (XNA C#) but for the life of me i cannot find an example of an overloaded method. Specifically i want to call a method with two or three parameters. if i call it with three parameters then the three parameter method needs to call the two parameter method and then do some additional work. if it was a constructor it would look like this;

public SpriteSheet(string a_sheet, string a_name)
{
    ...
}

public SpriteSheet(string a_sheet, string a_name, Color a_color):this(a_sheet, a_name)
{
    ...
}

Thanks in advance for your help.

È stato utile?

Soluzione

You need to call first method from the body of second method

public void SpriteSheetMethod(string a_sheet, string a_name)
{
 ...
}

public void  SpriteSheetMethod(string a_sheet, string a_name, Color a_color)
{
    SpriteSheet(a_sheet, a_name);
}

Altri suggerimenti

Instead of having logic in each constructor, ideal way of coding is that your method with Max parameters should be called from other constructors.

This way

public SpriteSheet(string a_sheet, string a_name)
{
    SpriteSheet(a_sheet, a_name, null);
}

public SpriteSheet(string a_sheet, Color a_color)
{
    SpriteSheet(a_sheet, null, a_color);
}

public SpriteSheet(string a_sheet, string a_name, Color a_color)
{
      // Your Logic of constructor should be here.
}

Instead of using an "overload" you could use a method with default value parameters:

public SpriteSheet(string a_sheet, string a_name="", Color a_color=Color.AliceBlue)
{
      // Your Logic should be here.
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top