Cool_Breeze 发表于 2021-2-24 18:26:36

开始学 C# 记录贴!

本帖最后由 Cool_Breeze 于 2021-2-25 21:02 编辑

汽车加油站! switch 使用
using System;
using System.Threading;

namespace Switch
{
    class He
    {
      static void Main()
      {
            double a = 6.8;
            double b = 6.42;
            double c = 7.02;
            double d = 5.75;
            Thread.Sleep(1000);
            Console.WriteLine("----------欢迎光临------");
            Console.WriteLine("请选择燃油种类");
            Console.WriteLine("1:90号\t 2:93号汽油\t3:97号汽油\t4:0号汽油");
            string n;
            He method = new He();
            n = Console.ReadLine();
            switch (n)
            {
                case "1":
                  Console.WriteLine("您选择的是90号汽油,价格为:{0}元/升", a);
                  method.Shen(a);
                  break;
                case "2":
                  Console.WriteLine("您选择的是93号汽油,价格为:{0}元/升", b);
                  method.Shen(b);
                  break;
                case "3":
                  Console.WriteLine("您选择的是97号汽油,价格为:{0}元/升", c);
                  method.Shen(c);
                  break;
                case "4":
                  Console.WriteLine("您选择的是90号柴油,价格为:{0}元/升", d);
                  method.Shen(d);
                  break;
                default:
                  Console.WriteLine("输入有误!");
                  break;
            }
            Console.ReadLine();
      }
      
      public double Shen(double mo)
      {
            Console.WriteLine("请输入您要购买多少升油,例如 5.5 代表您想要购买5.5升油!");
            string n1 = "";
            double n = 0;
            n1 = Console.ReadLine();
            Console.WriteLine("您所要购买的燃油量是:{0} 升", n1);
            n = Convert.ToDouble(n1) * mo;
            Console.WriteLine("请选择服务: A:自助加油    B:协助加油");
            n1 = Console.ReadLine();
            He zhe = new He();
            switch (n1)
            {
                case "A":
                  Console.WriteLine("您选择的是“自助加油”,优惠10%");
                  zhe.zhekou(ref n);
                  Console.WriteLine("您本次消费金额为:{0}", n*0.9);
                  break;
                default:
                  Console.WriteLine("您选择的是“协助加油”,优惠5%");
                  zhe.zhekou(ref n);
                  Console.WriteLine("您本次消费金额为:{0}", n*0.95);
                  break;
            }
            return n;
      }
      
      public void zhekou(ref double mo)
      {
            // double res = mo;
            if (mo < 600 && mo >200)
            {
                // res*=0.85;
                mo*=0.85;
            }
            else if (mo < 1000 && mo >600)
            {
                // res*=0.7;
                mo*=0.7;
            }
            else if (mo > 1000 )
            {
                // res*=0.6;
                mo*=0.6;
            }
            // return res;
      }
    }
}

Cool_Breeze 发表于 2021-2-25 21:03:14

using System;
using System.Collections;


namespace Girl
{
    // 抽象类
    public abstract class Animal
    {
      // 虚拟方法 子类中使用 override 重写父类方法
      public virtual void Cry(){
            Console.WriteLine("你听,动物在叫。。。");
      }
      // 未实现的虚拟方法 子类中使用 override 重写父类方法
      // 未实现的虚拟方法(抽象方法)必须写在抽象类里面
      public abstract void Eat();
    }
   
    // 继承自 Animal
    class Cat: Animal
    {
      // 使用 override 重写父类方法
      public override void Cry(){
            Console.WriteLine("你听,小猫在叫。。。");
      }
      // 使用 override 重写父类方法
      public override void Eat()
      {
            Console.WriteLine("你看,小猫在吃小鱼干。。。");
      }
    }
   
    // 继承自 Animal
    class Dog: Animal
    {
      // 使用 override 重写父类方法
      public override void Cry(){
            Console.WriteLine("你听,小狗在叫。。。");
      }
      // 使用 override 重写父类方法
      public override void Eat(){
            Console.WriteLine("你看,哦!小狗正在使劲舔,是吃不到吗!");
      }
    }
   
    class Pragma
    {
      static void Main(){
            // 注意 抽象类不能被实体化,new 子类就好了!
            // Animal 是Cat的基类,都可以申明变量
            Cat cat = new Cat();
            Animal dog = new Dog();
            cat.Cry();
            dog.Cry();
            cat.Eat();
            dog.Eat();
            Mans hua = new Mans("小明", "华子");
            hua.Man();
            hua.Women();
            Console.ReadLine();
            // 你听,小猫在叫。。。
            // 你听,小狗在叫。。。
            // 你看,小猫在吃小鱼干。。。
            // 你看,哦!小狗正在使劲舔,是吃不到吗!
            // 小明 和 华子 去了男厕所
            // 小明 和 华子 去了女厕所
      }
    }
   
    // 接口 声明
    public interface IWc
    {
      // 去厕所干嘛咱也不知道啊!
      // 女厕所
      void Women();
      // 男厕所
      void Man();
    }
   
    public class Mans: IWc
    {
      // 只读变量
      public readonly string sexm = "男厕所";
      public readonly string sexw = "女厕所";
         
      // 私有变量
      private string namea = string.Empty;
      private string nameb = string.Empty;
         
      // 构造函数
      public Mans(string a, string b){
            this.namea = a;
            this.nameb = b;
      }
         
      // 直接重写方法就行
      // 基接口的2个接口必须重写,不然无法编译
      public void Man(){
            Console.WriteLine("{0} 和 {1} 去了{2}", namea, nameb, sexm);
      }
      public void Women(){
            Console.WriteLine("{0} 和 {1} 去了{2}", namea, nameb, sexw);
      }
    }
}

Cool_Breeze 发表于 2021-2-25 21:04:18

语句 示例
// 局部变量声明
static void Main() {
    int a;
    int b = 2, c = 3;
    a = 1;
    Console.WriteLine(a + b + c);
}
// 局部常量声明
static void Main() {
    const float pi = 3.1415927f;
    const int r = 25;
    Console.WriteLine(pi * r * r);
}
// 表达式语句
static void Main() {
    int i;
    i = 123; // Expression statement
    Console.WriteLine(i);// Expression statement
    i++; // Expression statement
    Console.WriteLine(i);// Expression statement
}
// if 语句
static void Main(string[] args) {
    if (args.Length == 0) {
      Console.WriteLine("No arguments");
    }
    else {
      Console.WriteLine("One or more arguments");
    }
}
// switch 语句
static void Main(string[] args) {
    int n = args.Length;
    switch (n) {
      case 0:
            Console.WriteLine("No arguments");
            break;
      case 1:
            Console.WriteLine("One argument");
            break;
      default:
            Console.WriteLine("{0} arguments", n);
            break;
    }
}
// while 语句
static void Main(string[] args) {
    int i = 0;
    while (i < args.Length) {
      Console.WriteLine(args);
      i++;
    }
}
// do 语句
static void Main() {
    string s;
    do {
      s = Console.ReadLine();
      if (s != null) Console.WriteLine(s);
    } while (s != null);
}
// for 语句
static void Main(string[] args) {
    for (int i = 0; i < args.Length; i++) {
      Console.WriteLine(args);
    }
}
// foreach 语句
static void Main(string[] args) {
    foreach (string s in args) {
      Console.WriteLine(s);
    }
}
// break 语句
static void Main() {
    while (true) {
      string s = Console.ReadLine();
      if (s == null) break;
      Console.WriteLine(s);
    }
}
// continue 语句
static void Main(string[] args) {
    for (int i = 0; i < args.Length; i++) {
      if (args.StartsWith("/")) continue;
      Console.WriteLine(args);
    }
}
// goto 语句
static void Main(string[] args) {
    int i = 0;
    goto check;
    loop:
      Console.WriteLine(args);
    check:
      if (i < args.Length) goto loop;
}
// return 语句
static int Add(int a, int b) {
    return a + b;
}
static void Main() {
    Console.WriteLine(Add(1, 2));
    return;
}
// yield 语句
static IEnumerable<int> Range(int from, int to) {
    for (int i = from; i < to; i++) {
      yield return i;
    }
    yield break;
}
static void Main() {
    foreach (int x in Range(-10,10)) {
      Console.WriteLine(x);
    }
}
// throw 和 try 语句
static double Divide(double x, double y) {
    if (y == 0) throw new DivideByZeroException();
    return x / y;
}
static void Main(string[] args) {
    try {
      if (args.Length != 2) {
            throw new Exception("Two numbers required");
      }
      double x = double.Parse(args);
      double y = double.Parse(args);
      Console.WriteLine(Divide(x, y));
    }
    catch (Exception e) {
      Console.WriteLine(e.Message);
    }
    finally {
      Console.WriteLine(“Good bye!”);
    }
}
// checked 和 unchecked 语句
static void Main() {
    int i = int.MaxValue;
    checked {
      Console.WriteLine(i + 1); // Exception
    }
    unchecked {
      Console.WriteLine(i + 1); // Overflow
    }
}
// lock 语句
class Account
{
    decimal balance;
    public void Withdraw(decimal amount) {
      lock (this) {
            if (amount > balance) {
                throw new Exception("Insufficient funds");
            }
            balance -= amount;
      }
    }
}
// using 语句
static void Main() {
    using (TextWriter w = File.CreateText("test.txt")) {
      w.WriteLine("Line one");
      w.WriteLine("Line two");
      w.WriteLine("Line three");
    }
}

Cool_Breeze 发表于 2021-3-11 15:30:51

<委托>,遍历目录文件大小 过滤保存日志

using System;
using System.Windows.Forms;
using System.IO;
using System.Collections.Generic;

class DelegateExtension
{
    // 委托类型声明 返回值类型 string 类型名 MyDelegate 参数 digits 类型为 int
    public delegate string MyDelegate(int digits);
   
    static void Main()
    {
      // Test test = new Test();
         
      // 自定义委托
      // MyDelegate fu1 = new MyDelegate(test.fun1);
      // MyDelegate fu2 = new MyDelegate(Test.fun2);
      // MyDelegate fu1 = test.fun1;
      // MyDelegate fu2 = Test.fun2;
         
      // 系统封装好的不带返回值委托类
      // Action<string> fu3;
      // fu3 = test.fun3;
         
      // 系统封装好的带返回值的委托类
      // 方法返回值类型放在Func最后面
      // Func<int, string> fu1 = test.fun1;
      // Func<int, string> fu2 = Test.fun2;
         
      // Console.WriteLine(fu1(2));
      // Console.WriteLine(fu2(20));
      // fu3("GIN");
         
      string logPath = @"D:\GIN\c#\Exercise\log.log";
      // 实例默认输出至logPath
      FileLogger fileLogger = new FileLogger(logPath);
         
         
      // Console.WriteLine("日志级别:{0}", Logger.LogLevel);
      // Logger.LogMessage(Severity.Error, "Logger", "ERROR");
      // Logger.LogMessage(Severity.Warning, "Logger", "Warning");
      // 等级低于设置级别,不打印
      // Logger.LogMessage(Severity.Information, "Logger", "Information");
         
      // 卸载LogPath.LogMessage, 将不会输出之文本
      // fileLogger.DetachLog();
      // Logger.LogLevel = Severity.Information;
      // Console.WriteLine("日志级别:{0}", Logger.LogLevel);
      // Logger.LogMessage(Severity.Information, "Logger", "Information");
         
      FileInformation target = new FileInformation(@"D:\");
         
      // 修改日志级别
      Logger.LogLevel = Severity.Information;
      Console.WriteLine("日志级别:{0}", Logger.LogLevel);
         
      // 不在控制台输出
      // 从多播委托中卸载控制台输出
      Logger.WriteMessage -= Console.WriteLine;
         
      // 扫描之前设置一下过滤文件的大小
      // 文件小于 1M 的将被记录
      target.filterFileSizeKB = 1024;
      // 开始扫描
      target.StartScan();
         
    }
   
    // logger 输出级别
    public enum Severity
    {
      Verbose,
      Trace,
      Information,
      Warning,
      Error,
      Critical
    }
   
    // 日志输出
    public static class Logger
    {
      // 静态类中也不能出现实例的字段成员
      // 静态类的字段需要在编译前赋值, 不能在运行时赋值, 除了它的属性
      // 消息处理处理委托,参数为 string
         
      // 默认输出至控制台
      public static Action<string> writeMessage = Console.WriteLine;
      public static Action<string> WriteMessage{get{return writeMessage;} set {writeMessage = value;}}
         
      // 日志输出等级设置
      private static Severity logLevel = Severity.Warning;
         
      // 设置字段属性
      public static Severity LogLevel{get{return logLevel;} set {logLevel = value;}}
         
         
      // 判断输入日志是否满足日志输出等级 (需要三个参数)
      public static void LogMessage(Severity s, string component, string msg)
      {
            // 设置日志级别小于 logLevel 级别跳过
            if (s < logLevel)
            {
                return;
            }
            
            // 设置日志级别大于等于 Warning 将在控制台输出
            // 这里有个 BUG 没有检查多播链中是否已经存在这个方法
            if (s >= Severity.Warning)
            {
                writeMessage += Console.WriteLine;
                writeMessage(String.Format("{0}\t{1}\t{2}", DateTime.Now, component, msg));
                writeMessage -= Console.WriteLine;
                return;
            }
            
            // 调用日志输出方法
            // String.Format 将返回一个字符串,传入 writeMessage 委托的方法
            writeMessage(String.Format("{0}\t{1}\t{2}", DateTime.Now, component, msg));
      }
         
    }
   
    // 输出日志到本地文件
    public class FileLogger
    {
      private readonly string logPath;
      public FileLogger(string path)
      {
            logPath = path;
            // 加入 追加模式写入文本方法(多播委托)
            Logger.WriteMessage += LogMessage;
      }
         
      // 追加模式写入文本 utf-8
      public void LogMessage(string msg)
      {
            try
            {
                using (var log = File.AppendText(logPath))
                {
                  log.WriteLine(String.Format("{0}", msg));
                  log.Flush();
                }
            }
            catch
            {
                  Console.WriteLine("记录日志到 {0} 文件中失败!", logPath);
            }
      }
         
      // 卸载 LogMessage
      public void DetachLog()
      {
            Logger.writeMessage -= LogMessage;
      }
    }
   

    // 文件信息扫描
    public class FileInformation
    {
      // 扫描文件夹路径
      public string TargetDirectory{get;set;}
         
      public FileInformation(string dir)
      {
            this.TargetDirectory = dir;
      }
         
      // 这个可以设置成其他容量,需要转换
      // 设置过滤文件大小
      public float filterFileSizeKB = 0;
      public float FilterFileSizeKB
      {
            get
            {
                return filterFileSizeKB;
            }
            set
            {
                this.filterFileSizeKB = value;
            }
      }
         
      // 指定不可访问的目录
      public List<string> skipList = new List<string>{@"$RECYCLE.BIN", @"System Volume Information"};
         
      // value 的值是 List<string> 类型
      public List<string> SkipList
      {
            get
            {
                return this.skipList;
            }
            set
            {
                // 这里可以检查一下列表里面是否已经存在
                foreach (var str in value)
                {
                  // 不存在,则加入
                  if (this.skipList.IndexOf(str) == -1)
                        this.skipList.Add(str);
                }
            }
      }
         
      public bool StartScan()
      {
            DirectoryInfo dir;
            // 处理报错
            try
            {
                dir = new DirectoryInfo(this.TargetDirectory);      
                decimal count = 0; // 文件计数
                bool flag = false;
                foreach (var each in dir.GetDirectories())
                {
                  flag = false;
                  // 查询是否包含不可访问目录
                  foreach (var sikp in this.skipList)
                  {
                        if (each.FullName.Contains(sikp))
                        {
                            flag = true;
                            // 开启记录日志
                            Logger.LogMessage(Severity.Warning, "FileInformation", String.Format("{0}跳过指定目录:{1}", DateTime.Now, each.FullName));
                            break;
                        }
                  }
                     
                  if (flag) continue;
                     
                  DirectoryInfo eachDir = new DirectoryInfo(each.FullName);
                  // 在搜索操作中包括当前目录和所有它的子目录。 此选项在搜索中包括重解析点,比如安装的驱动器和符号链接。
                  foreach (System.IO.FileInfo fi in eachDir.GetFiles("*.*", System.IO.SearchOption.AllDirectories))
                  {
                        count++;
                        // 这里只记录文件大小 小于 指定文件大小
                        // 其他的还可以增加
                        if (fi.Length < this.FilterFileSizeKB)
                            // 开启记录日志
                            Logger.LogMessage(Severity.Information, "FileInformation", String.Format("{0},{1},{2}",count, fi.FullName, fi.Length));
                  }
                }
            }
            catch (Exception err)
            {
                Logger.LogMessage(Severity.Error, "FileInformation", err.Message);
                return false;
            }
            // 暂且返回真
            return true;
      }
         
      // 加入日志
      public void FromLog(FileLogger obj)
      {
            Logger.writeMessage += obj.LogMessage;
      }
         
      // 移除日志
      public void DetachLog(FileLogger obj)
      {
            Logger.writeMessage -= obj.LogMessage;
      }
    }
   
   
    public class Test
    {
      public void fun3(string name)
      {
            MessageBox.Show(String.Format("Hello {0} !", name));
      }
         
      public string fun1(int digits)
      {
            if (digits > 10)
            {
                return String.Format("{0} > 10", digits);
            }
            else
            {
                return String.Format("{0} < 10", digits);
            }
      }
         
      public static string fun2(int digits)
      {
            if (digits > 10)
            {
                return "GEQ";
            }
            else
            {
                return "LEQ";
            }
      }
    }
}

Cool_Breeze 发表于 2021-3-11 15:32:14

命令行复制文件和目录
using System;
using System.IO;
using System.Collections.Generic;
using Microsoft.VisualBasic.FileIO;

class CopyFileExercise
{
    static void Main (string[] args)
    {
      ConmandLineEventArgs Margs = new ConmandLineEventArgs(args); // 参数实例
         
      ConmandLineParse clp = new ConmandLineParse(); // 解析命令行
      clp.Parse(Margs);
         
      new CopyDirectoryOrFile(Margs).Copy(); // 复制文件
    }
   
    // 储存参数数据
    public class ConmandLineEventArgs : EventArgs
    {
      public readonly string sourceMatch = "-source:"; // 只读字段
      public readonly string destinationMatch = "-destination:";
      public string[] Args;
      public string source{ get; set;} // 主要储存数据字段
      public string destination{ get; set;} // 主要储存数据字段
      public string Error;
         
      public ConmandLineEventArgs(string[] args)
      {
            this.Args = args;
      }
    }
   
    static void CLParseEventHandler(object sender, ConmandLineEventArgs e)
    {
      Console.WriteLine(e.Error);
      Console.WriteLine("参数用法:\n\n\t{0}源文件名(或者源目录名)\n\t{1}新文件名(或者新目录名)", e.source, e.destination);
      Environment.Exit(1); // 退出进程
    }
   
    // 命令行解析
    class ConmandLineParse
    {
         
      public ConmandLineParse()
      {
            this.ErrorEvent += CLParseEventHandler; // 默认订阅事件处理器
      }
         
      public event EventHandler<ConmandLineEventArgs> ErrorEvent; // 错误事件
         
      public void Parse(ConmandLineEventArgs e)
      {
            if (e.Args.Length != 2) // 检查参数数量
            {
                e.Error = "输入参数数量错误";
                this.OnErrorEvent(e);
            }
            
            foreach (var n in e.Args) // 分析参数
            {
                if (n.StartsWith(e.sourceMatch))
                {
                  e.source =n.Replace (e.sourceMatch, ""); // 源数据
                }
                else if (n.StartsWith(e.destinationMatch))
                {
                  e.destination = n.Replace (e.destinationMatch, ""); // 目标数据
                }
            }
            
            // 检查数据是否为空
            if (e.source == "")
            {
                e.Error = "source为空";
                this.OnErrorEvent(e);
            }
            if (e.destination == "")
            {
                e.Error = "destination为空";
                this.OnErrorEvent(e);
            }
      }
         
      private void OnErrorEvent(ConmandLineEventArgs e) // 参数不正确事件触发
      {
            this.ErrorEvent(this, e);
      }
    }
   
    // 文件或者目录复制
    public class CopyDirectoryOrFile
    {
      private ConmandLineEventArgs e;
      private event EventHandler<ConmandLineEventArgs> ErrorEvent; // 事件
         
      public CopyDirectoryOrFile(ConmandLineEventArgs e)
      {
            this.e = e;
            this.ErrorEvent += CLParseEventHandler; // 事件订阅
      }
         
         
      public void Copy()
      {
            // 调用不同的复制方法
            try
            {
                if (File.Exists(this.e.source))
                {
                   FileSystem.CopyFile(this.e.source, this.e.destination, UIOption.AllDialogs, UICancelOption.DoNothing); // 用户取消不引发异常
                }
                else if (Directory.Exists(this.e.source))
                {
                  FileSystem.CopyDirectory(this.e.source, this.e.destination, UIOption.AllDialogs, UICancelOption.DoNothing);
                }
                else
                {
                  this.e.Error = String.Format("{0} 既不是文件也不是目录", e.source);
                  ErrorEvent(this, this.e);
                }
            }
            catch (IOException E)
            {
                this.e.Error = E.Message; // 获取异常的信息
                ErrorEvent(this, this.e);
            }
      }
    }
}

batch shell
@echo off

echo;
echo ##############################
echo ## 穿越火线和英雄联盟备份 ###
echo ##############################
echo;

echo 输入 ^<Q^> 退出
echo 输入 ^<L^> 备份英雄联盟
echo 输入 ^<C^> 备份穿越火线
echo 输入 ^<T^> 备份穿越火线和英雄联盟
echo;
echo 请输入字母不区分大小写:
choice /c QLCT /n
set result=%errorlevel%
if %result% equ 1 exit
if %result% equ 2 call :BackupLOL
if %result% equ 3 call :BackupCF
if %result% equ 4 call :BackupTotal

pause
exit 0

:BackupLOL
    CopyFile.exe -source:"C:\user\英雄联盟" -destination:"D:\腾讯游戏\英雄联盟"
    exit /b

:BackupCF
    CopyFile.exe -source:"C:\user\穿越火线" -destination:"D:\腾讯游戏\穿越火线"
    exit /b

:BackupTotal
    call :BackupLOL
    call :BackupCF
    exit /b

hrp 发表于 2021-3-11 18:55:06

学习

Cool_Breeze 发表于 2021-3-12 18:04:31

运算符重载:
using System;

namespace Operator
{
    class Program
    {
      static void Main()
      {
            Box a = new Box(2);
            Box b = new Box(3);
            
            Console.WriteLine(a + b);// 5 这里返回一个新的 Box 实例,但是被丢弃了
            Console.WriteLine(a >= b); // false
            Console.WriteLine(a <= b); // true
            Console.WriteLine(a++);    // 12 重载时 我们把 Count 的值加上了 10
            Console.WriteLine(a--);    // 7重载时 我们把 Count 的值减去了 5
            Console.WriteLine(+a);   // 7
            Console.WriteLine(-a);   // -7
            Console.WriteLine(!a);   // False
            a.Count += 7;            // a.Count = 0
            Console.WriteLine(a);      // 0
            Console.WriteLine(!a);   // true
            Console.WriteLine(a++);    // 10
            Console.WriteLine(~a);
            // 取反前二进制码:
            // 00000000,00000000,00000000,00001010
            // 取反后二进制码:
            // 11111111,11111111,11111111,11110101
            // -11
      }
    }
   
   
    class Box
    {
      public int Count {get; set;}
         
      public Box(int v)
      {
            Count = v;
      }
         
      // 重写 ToString 方法 ToString 继承自 object
      // Console.WriteLine 会直接输出 Count 的值;
      public override string ToString()
      {
            return String.Format("{0}", Count);
      }
         
      // 二元操作符 + 需要两个参数
      // 两个相同对象相加,返回相同类型实例 static 修饰符后面的 Box 就是返回值 类型
      public static Box operator + (Box a, Box b)
      {
            Box c = new Box(0);
            c.Count = a.Count + b.Count;
            return c;
      }
         
      // >= 和 <= 必须成对出现,不然会报编译错误 返回值类型为 bool
      public static bool operator >= (Box a, Box b)
      {
            
            if (a.Count >= b.Count)
            {
                return true;
            }
            else
            {
                return false;
            }
      }
         
      public static bool operator <= (Box a, Box b)
      {
            if (a.Count <= b.Count) return true;
            else return false;
      }
         
         
         
      // 一元操作符 + 只需要一个参数
      public static Box operator + (Box a)
      {
            a.Count = Math.Abs(a.Count);
            return a;
      }
         
      public static Box operator - (Box a)
      {
            a.Count = 0 - a.Count;
            return a;
      }
         
      // 定义 Count 的值 等于 0 或者 等于 null 时,Count 的值为 false 然后取反 为 true
      public static bool operator ! (Box a)
      {
            if (a.Count == 0 || (int?)a.Count == null) // 值为 false (int?)显示类型转换
            {
                return true; // 取反返回 true
            }
            else return false;
      }
         
      // 自增运算符不需要创建一个实例,使用它自己
      public static Box operator ++ (Box a)
      {
            a.Count += 10;
            return a;
      }
         
      public static Box operator -- (Box a)
      {
            a.Count -= 5;
            return a;
      }
         
      // 按位取反
      public static Box operator ~ (Box a)
      {
            Console.WriteLine("取反前二进制码:");
            DisplayBinary(a.Count);
            a.Count = ~a.Count;
            Console.WriteLine("取反后二进制码:");
            DisplayBinary(a.Count);
            return a;
      }

      public static void DisplayBinary(int Number) // 显示二进制位
      {
            unsafe // 不安全代码 指针
            {
                int Count = Number; // int 4 个字节
                byte* p = (byte*)&Count;// byte 1个字节
                for (sbyte i = 3; i >= 0; i--)
                {
                  for (sbyte j = 7; j >= 0; j--) // 一个字节等于 8 个比特位
                  {
                        if (((*(p + i) & (1<<j))) != 0)
                        {
                            Console.Write(1);
                        }
                        else
                        {
                            Console.Write(0);
                        }
                  }
                  if (i != 0) Console.Write(',');
                }
            }
            Console.Write('\n');
            
            // for (sbyte i = 31; i >= 0; i--) // 不使用指针版
            // {
                // if ((Number & (1<<i)) != 0)
                // {
                  // Console.Write(1);
                // }
                // else
                // {
                  // Console.Write(0);
                // }
            // }
      }

    }
}
页: [1]
查看完整版本: 开始学 C# 记录贴!