如何重载方法

时间:2014-04-07 07:16:02

标签: c# methods overloading

我已经看了很多,我理解如何重载构造函数(XNA C#),但对于我的生活,我找不到重载方法的示例。具体来说,我想调用一个带有两个或三个参数的方法。如果我用三个参数调用它,那么三参数方法需要调用两个参数方法然后做一些额外的工作。如果它是一个构造函数,它看起来像这样;

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

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

提前感谢您的帮助。

3 个答案:

答案 0 :(得分:4)

您需要从second方法

的正文中调用第一个方法
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);
}

答案 1 :(得分:1)

不是在每个构造函数中都有逻辑,理想的编码方式是应该从其他构造函数调用具有Max参数的方法。

这样

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.
}

答案 2 :(得分:0)

而不是使用"重载"您可以使用具有默认值参数的方法:

public SpriteSheet(string a_sheet, string a_name="", Color a_color=Color.AliceBlue)
{
      // Your Logic should be here.
}
相关问题