本示例演示了如何使用允许在两个或更多 C# 文件中定义类或结构的分部类型。这就允许多个程序员并行处理一个类的不同部分,并将复杂类的不同方面保存在不同的文件中。
CharTypesPrivate.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace PartialClassesExample
{
// 使用 partial 关键字可以在其他 .cs 文件中定义
// 此类的附加方法、字段和属性。
// 此文件包含 CharValues 定义的私有方法。
partial class CharValues
{
private static bool IsAlphabetic(char ch)
{
if (ch >= 'a' && ch <= 'z')
return true;
if (ch >= 'A' && ch <= 'Z')
return true;
return false;
}
private static bool IsNumeric(char ch)
{
if (ch >= '0' && ch <= '9')
return true;
return false;
}
}
}
CharTypesPublic.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace PartialClassesExample
{
// 使用 partial 关键字可以在其他 .cs 文件中定义
// 此类的附加方法、字段和属性。
// 此文件包含 CharValues 定义的公共方法。
partial class CharValues
{
public static int CountAlphabeticChars(string str)
{
int count = 0;
foreach (char ch in str)
{
// IsAlphabetic 是在 CharTypesPrivate.cs 中定义的
if (IsAlphabetic(ch))
count++;
}
return count;
}
public static int CountNumericChars(string str)
{
int count = 0;
foreach (char ch in str)
{
// IsNumeric 是在 CharTypesPrivate.cs 中定义的
if (IsNumeric(ch))
count++;
}
return count;
}
}
}
PartialTypes.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace PartialClassesExample
{
class PartialClassesMain
{
static void Main(string[] args)
{
if (args.Length != 1)
{
Console.WriteLine("One argument required.");
return;
}
// CharValues 是一个分部类 -- 该分部类有两个方法
// 是在 CharTypesPublic.cs 中定义的,另有两个方法是在
// CharTypesPrivate.cs 中定义的。
int aCount = CharValues.CountAlphabeticChars(args[0]);
int nCount = CharValues.CountNumericChars(args[0]);
Console.Write("The input argument contains {0} alphabetic and {1} numeric characters", aCount, nCount);
}
}
}
