【问题标题】:how to overload a method如何重载一个方法
【发布时间】:2014-04-07 07:16:02
【问题描述】:

我环顾四周,了解如何重载构造函数 (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)
{
    ...
}

提前感谢您的帮助。

【问题讨论】:

  • 为什么不直接从三参数方法中调用二参数方法呢?

标签: c# methods overloading


【解决方案1】:

你需要从second方法体中调用first方法

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);
}

【讨论】:

  • 非常感谢。这两个答案都很好
【解决方案2】:

最好的编码方式是从其他构造函数调用具有 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.
}

【讨论】:

  • 非常感谢。这两个答案都很好
【解决方案3】:

您可以使用带有默认值参数的方法,而不是使用“重载”:

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

【讨论】:

    猜你喜欢
    • 2016-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-20
    相关资源
    最近更新 更多