2010-07-02 229 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