Partial Class verse Partial Method

I.**Partial Class
1.定义:部分类允许我们把一个类拆分为2个或者多个文件,然后编译时合成为一个文件
2.Partial关键字能用在class,struct,interface
3.部分类的好处:

1.VS用部分类来分开开发者代码和系统自动生成的代码,如:webForm1.aspx.cs和WebForm1.aspx.designer.cs
2.开发大项目时,可以同时工作

4.实例:

部分类1:
namespace ParialClassDemo
{
    public partial class PartialStudent
    {
        public string GetFullName(string s1,string s2)
        {
            return s1 + s2;
        }
    }
}

部分文件2:
namespace ParialClassDemo
{
   public  partial class PartialStudent
    {
        private string _firstName;

        public string FirstName
        {
            get { return _firstName; }
            set { _firstName = value; }
        }
        private string _lastName;

        public string LastName
        {
            get { return _lastName; }
            set { _lastName = value; }
        }
    }
}

5.部分类使用注意地方

1.All the parts spread across different files,//must use the partial keyword;
2.All the parts spread across different files,//must have the same access modifier(public or internal);
3.If any of the parts are declared abstract,//then the entire type is considered abstract;
4.If any of the parts are declared sealed,//then the entire type is considered sealed(密封类不能被继承);
5.If any of the parts inherit a class,//then the entire type inherits that calss;
6.C# does not support multiple class inheritance.Different parts of the partial class,must not specify different base class;
7.Different parts of the partial class can specify different base interfaces,and the final type implements all of the interfaces listed by all of the partial declarations;
8.Any members that declared in a partial definition are available to all of the other parts of the partial class;

II**Partial Method**
1.部分方法将方法分为方法声明和方法体,部分方法

使用部分方法注意地方:

1.A partial class or a struct can contain partial methods;
2.A partial method is create using the partial keyword;
3.A partial method declaration consists of two parts.定义(只有签名部分)和实行部分(可选,可写可不写),可以将这两个部分写在同一个部分类中,也可以写在不同部分类中
eg.
   partial void SamplePartialMethod();//声明部分
   partial void SamplePartialMethod()
   {Console.WriteLine("hello")};//实现部分
4.The implementation for partial method is optional .If we don't provide the implementation ,the compiler removes the signature and all calls to the method.实现部分可写可不写,不写,编译器自动忽略
5.Partial methods are private by default .部分方法默认是private的,不能添加访问修饰符
   public/private void SamplePartialMethod();//错误写法
6.部分方法必须包含声明部分,直接写实现部分是错误的
    partial void SamplePartialMethod()
   {Console.WriteLine("hello")};//错误写法,缺少声明部分
7.部分方法的返回类型必须是void,其余返回类型报错
8.部分方法只能在部分类(Partial classes)或部分结构(partial structures)中   
9.部分方法只能实现一次。尝试实现多次会报错  

你可能感兴趣的:(C#学习)