2017-07-10 44 views
2

我有兩個具有相同名稱的函數,主要區別僅僅是不同的返回類型。我怎麼能以使用相同的名稱,因爲有時我需要三維點或point3f陣列重載函數,下面的函數名給出錯誤是相同的:具有不同返回類型的超載函數

public static Point3d[] GetNGonCenters(this Mesh mesh) 
{ 
    Point3d[] centers = new Point3d[mesh.Ngons.Count]; 

    for (int i = 0; i < mesh.Ngons.Count; i++) 
     centers[i] = mesh.Ngons.GetNgonCenter(i); 

    return centers; 
} 

public static Point3f[] GetNGonCenters(this Mesh mesh) 
{ 
    Point3f[] centers = new Point3f[mesh.Ngons.Count]; 

    for (int i = 0; i < mesh.Ngons.Count; i++) 
     centers[i] = (Point3f)mesh.Ngons.GetNgonCenter(i); 

    return centers; 
} 
+8

你只能超負荷方法參數,而不是返回類型。 – Phylogenesis

+1

你不能在返回類型上重載函數 – ali

+0

另一種選擇是爲擴展方法創建一個不同的靜態類。如果它們位於不同的類中,則重載不會成爲問題。 – RobPethi

回答

6

編譯器無法知道你的方式正在打電話。我建議把名字更具描述性的,像這樣:

public static Point3d[] GetNGonCenters3D(this Mesh mesh) 

而且

,因爲它們可以使用相同的參數都
public static Point3f[] GetNGonCenters3F(this Mesh mesh) 

重載不會在這裏工作,編譯器無法猜測你想要的返回類型。

0

如果你想重載一個函數,你必須擁有一個具有相同名字的函數,就像你有的一樣,但是參數不同。你不會重載你的函數,因爲它們具有相同的名字和相同的參數。您必須重新命名該函數或向其中的一個添加新參數。

0

您可以使用泛型:

public static T[] GetNGonCenters<T>(this Mesh mesh) where T : Point3d 
{ 
    T[] centers = new T[mesh.Ngons.Count]; 

    for (int i = 0; i < mesh.Ngons.Count; i++) 
     centers[i] = (T)mesh.Ngons.GetNgonCenter(i); 

    return centers; 
} 

希望這有助於。

0

您不能重載兩個函數,唯一的區別是返回類型。 C#使用參數列表作爲上下文。

兩個想法:

  1. 你可以讓函數返回一個對象,並在呼叫類型轉換它。
  2. 您可以在標題中包含一個虛擬變量以區分方法上下文。

這裏是一篇關於C#重載的論文的好鏈接。 Overloading in depth

0

您不能通過只有不同的返回類型重載一個方法。當您按名稱調用它併爲其提供參數時,會發現一種方法,而不是您希望返回的對象。

考慮下面的例子(注意,它不會編譯)會發生什麼:

public class Foo 
{ 
    public int Number { get; set; } 

    private void DoSomething(int num) 
    { 
     Number += num; 
    } 

    private int DoSomething(int num) 
    { 
     // Bad example, but still valid. 
     Number = num + 2; 
     return num * num; 
    } 
} 

var foo = new Foo(); 

// Which version of the method do I want to call here? 
// Most likely it is the one that returns void, 
// but you can ignore the return type of any method call. 
foo.DoSomething(3); 
相關問題