2010-07-02 227 views
9

部分類我有一個部分類這樣具有相同名稱的方法

public partial class ABC 
{ 
    public string GetName() 
    { 
    //some code here 
    } 

    public string GetAge() 
    { 
    //some code here 
    }  
} 

public partial class ABC 
{ 
    public string GetSex() 
    { 
    //some code here 
    } 

    public string GetAge() 
    { 
    //some code here 
    }  
} 

如何在構建時這2類合併?請給我解釋一下。

回答

16

當您嘗試編譯此代碼時,將會出現編譯時錯誤

在編譯的時候會發生什麼是compiler結合了的所有部分的定義定義成一個的所有成員。然後它會嘗試按通常的方式進行編譯。

在你的情況下,將引發錯誤您已經定義具有相同名稱的方法。

6

它不能編譯,因爲在一個類中不能有兩個同名的方法。

+0

如果2個不同的用戶在這些類上工作,他們可以做這個錯誤,我可以防止這種情況。 – Pankaj 2010-07-02 10:56:18

+6

@Pankaj:讓他們互相交談=) – Jens 2010-07-02 10:57:11

+1

@Pakaj - 擁有一個良好的持續集成系統,不允許他們檢查無法編譯的代碼。 – cjk 2010-07-02 10:57:16

2

即使除了語法錯誤,代碼也不會編譯。您會收到以下錯誤:

Type 'MyNamespace.ABC' already defines a member called 'GetAge' with the same parameter types

這是因爲編譯器的部分類的所有部分合併成一個類作爲 科C#語言規範的10.2解釋說:

With the exception of partial methods (§10.2.7), the set of members of a type declared in multiple parts is simply the union of the set of members declared in each part. The bodies of all parts of the type declaration share the same declaration space (§3.3), and the scope of each member (§3.7) extends to the bodies of all the parts.

C#將不允許在同一個類中擁有相同名稱和相同數量和類型參數的方法。這是在規範的第1.6.6規定:

The signature of a method must be unique in the class in which the method is declared. The signature of a method consists of the name of the method, the number of type parameters and the number, modifiers, and types of its parameters. The signature of a method does not include the return type.

有一個選項,雖然到方法的聲明添加到部分類的一個組成部分和實現到另一個:局部方法。您可以閱讀埃裏克利珀的博客文章更多關於他們對話題:

What's the difference between a partial method and a partial class?

0

他們不合並:你將有一個編譯時錯誤。

0

它們不會合並:編譯時錯誤。如果您不小心將它們放入不同的命名空間,它們可能會合並在您的案例中。

0

預處理器(或編譯器也許)在他的某個運行過程中掃描您的項目文件夾,並檢查項目中的類名稱(或精確地說是程序集)。然後它標記部分類並檢查它們是否有多重定義。
向Eric Lippert詢問細節。然後它將合併方法,註釋,屬性,成員,接口等。 在c#lang規範中有讀取。 你的方法沒有局部修改,所以在我之前發現的人,它不會編譯。

1

部分類在編譯期間合併。 編譯器查找部分類並在編譯時將其集成。它只是將「兩個」部分類組合成一個類。 CLR沒有修改部分類的實現。你可以認爲它就像合併「兩個」部分類一樣。

例如你的代碼,你將擁有:

public partial class ABC 
{ 
    public string GetName() 
    { 
    //some code here 
    } 

    public string GetAge() 
    { 
    //some code here 
    } 

    public string GetSex() 
    { 
    //some code here 
    } 

    public string GetAge() 
    { 
    //some code here 
    } 
} 

而且它會給你一個錯誤,因爲你不能有2種方法具有相同的名稱和簽名(見GetAge方法)。

0

試試這個:

public class ABC 
{ 
    public string GetName() 
    { 
    //some code here 
    } 

    public string GetAge() 
    { 
    //some code here 
    } 
} 

public partial class ABC 
{ 
    public string GetSex() 
    { 
    //some code here 
    } 

    public string GetAge() 
    { 
    //some code here 
    }  
} 

離開部分出一流的!

+0

此代碼將不起作用,將給出以下錯誤,「對'ABC'類型的聲明缺少部分修飾符;此類型的另一個部分聲明存在」 – 2016-05-03 12:59:11