2014-04-07 25 views
0

我已經看了很多,我明白如何重載構造函數(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) 
{ 
    ... 
} 

在此先感謝您的幫助。

+0

爲什麼不直接調用來自三個參數方法兩個參數的方法? – AlphaDelta

回答

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

非常感謝。這兩個答案都很好 – blink

1

而是在每個構造有邏輯的,編碼的理想方式是,用最高參數的方法應該從其他構造函數調用。

這樣

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

非常感謝。這兩個答案都很好 – blink

0

而不是使用「過載」,你可以使用默認值參數的方法:

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