• 欢迎访问开心洋葱网站,在线教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入开心洋葱 QQ群
  • 为方便开心洋葱网用户,开心洋葱官网已经开启复制功能!
  • 欢迎访问开心洋葱网站,手机也能访问哦~欢迎加入开心洋葱多维思维学习平台 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~!
  • 由于近期流量激增,小站的ECS没能经的起亲们的访问,本站依然没有盈利,如果各位看如果觉着文字不错,还请看官给小站打个赏~~~~~~~~~~~~~!

C#将一个类的不同部分分布在不同的文件中的方法

OC/C/C++ 水墨上仙 1328次浏览

本示例演示了如何使用允许在两个或更多 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);
        }
    }
}


开心洋葱 , 版权所有丨如未注明 , 均为原创丨未经授权请勿修改 , 转载请注明C#将一个类的不同部分分布在不同的文件中的方法
喜欢 (0)
加载中……