📅  最后修改于: 2020-11-01 03:00:52             🧑  作者: Mango
C#提供了一种概念,可以将源代码编写在单独的文件中,然后将其编译为一个单元。此功能称为部分类型,并包含在C#2.0中。局部关键字用于创建局部类型。
它允许我们在两个或更多单独的源文件中编写部分类,接口,结构和方法。编译应用程序时,将所有部分组合在一起。
让我们来看一个例子。在这里,我们正在创建一个部分类,该类包括在Customer.cs文件中的depositeAmount()函数和在Customer2.cs文件中的withdraw()函数。这两个函数都存储在单独的文件中,并在编译时合并。
// Customer.cs
using System;
namespace CSharpFeatures
{
partial class Customer
{
// Deposit function
public void depositAmount(int d_amount)
{
amount += d_amount;
Console.WriteLine(d_amount+" amount is deposited");
Console.WriteLine("Available balance is: "+amount);
}
}
}
// Customer2.cs
using System;
namespace CSharpFeatures
{
partial class Customer
{
private int amount;
public int Amount { get => amount; set => amount = value; }
// Withdraw function
public void withdraw(int w_amount)
{
amount -= w_amount;
Console.WriteLine(w_amount+" is withdrawn");
Console.WriteLine("Available balance is: "+amount);
}
}
}
using System;
namespace CSharpFeatures
{
class Program
{
static void Main(string[] args)
{
Customer customer = new Customer();
customer.Amount = 2000;
Console.WriteLine("Current balance is: "+ customer.Amount);
customer.depositAmount(1000);
// Accessing seperate file function
customer.withdraw(500);
}
}
}
输出:
Current balance is: 2000
amount is deposited
Available balance is: 3000
500 is withdrawn
Available balance is: 2500