C#重载运算符详解

 更新时间:2014年08月25日 08:54:14   投稿:shichen2014  
这篇文章主要介绍了C#重载运算符,是进行C#程序设计中非常重要的一个技巧,需要的朋友可以参考下

本文较为详细的描述了重载运算符的方法。一般来说,重载运算符在实际的项目开发中会经常的用到,但如果某些自定义类型通过简短几行代码重载一些常用的运算符(如:+-*/),就能让编程工作带来方便;重载运算符就是告诉编译器+-*/等运算符对于自定义类型进行什么样的操作,在代码中需要注意几点。

一、尽可能的不要改变运算符本身的含义

二、所有的运算符重载都必须声明为public和static

三、不同于扩展方法,所重载的方法必须是在被重载的类型内部,且用关键字operator

C#中的两个字符串相加,实际上是连接两个字符串,假如有两个EmployeeDetail类型相加得到一个EmployeeCollection集合,如:

EmployeeDetail a,b;

....

EmployeeCollection collection = a+b;

当编译器遇到上面的代码时就会自动调用EmployeeDetail类上标有operator +的静态方法,并将两个操作数a和b作为参数传递给对于的方法,该方法需要方法一个值赋给collection,假设EmployeeDetail类有三个属性分别是FirstName,MiddleName,LastName,还重写了ToString方法返回一个连接这三个名称的字符串,代码如:

[Serializable]
 public class EmployeeDetail
 {
   public string FirstName { get; set; }
   public string MiddleName { get; set; }
   public string LastName { set;get; }
   public override string ToString()
   {
     return string.Format("{0}{1}{2}{3}{4}", FirstName, string.IsNullOrWhiteSpace(MiddleName) ? null : "."
       , MiddleName
       , string.IsNullOrWhiteSpace(LastName) ? null : ".",
       LastName).Trim();
   }
 }

下面的代码为“+”运算符提供支持的运算符重载:

public static EmployeeCollection operator +(EmployeeDetail a, EmployeeDetail b)
{
  return new EmployeeCollection() { a, b };
}

OK,给EmployeeDetail类加上这样的一个方法之后,我们就可以像下面那个写代码了:

EmployeeCollection collection = new EmployeeDetail(){FirstName="Jackson",LastName="Bruce"} + new EmployeeDetail(){FirstName="Michael",LastName="Jackson"} ;

但是这样还不够完美,假设a,b,c都是EmployeeDetail类型,下面的代码会抛出一个编译错误:

EmployeeCollection collection = a + b + c;

为什么编译不通过呢?大家都知道除了赋值运算符外表达式是从左到右执行的,a+b返回的是EmployeeCollection类型,EmployeeCollection类型并没有重载“+”运算符,编译器不知道要执行什么操作,所以我们还有下面的两个方法:

public static EmployeeCollection operator +(EmployeeCollection collection, EmployeeDetail a)
{
  collection.Add(a);
  return collection;
}
public static EmployeeCollection operator +(EmployeeDetail a, EmployeeCollection collection)
{
  return collection + a;
}

这看起来似乎已经很完美了,但我们还可以做得更好一些,比如要将字符串“Jackson.Bruce”直接隐式转换为EmployeeDetail类型,也就是说可以将“Jackson.Bruce"这种格式的字符串直接赋给EmployeeDetail类型的对象,如:EmployeeDetail employee= “Jackson.Bruce",那么就需要重载隐式类型转换运算符了,代码如下:

/// <summary>
/// 隐式类型转换
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static implicit operator EmployeeDetail(string name)
{
       /// 其实在这里可以写一个正则表达式检查name的字符串格式是否合法,如果不合法就抛出异常
       ///
  string[] arr;
  return string.IsNullOrWhiteSpace(name) ? null :
 new EmployeeDetail()
 {
   FirstName = (arr = name.Trim().Split('.'))[0]
   ,
   LastName = arr.Length > 1 ? arr[arr.Length > 2 ? 2 : 1] : null,
   MiddleName = arr.Length > 2 ? arr[1] : null
 };
}
public static EmployeeCollection operator +(EmployeeDetail a, string b)
{
  return new EmployeeCollection() { a, b };
}

看到这里您是不是迫不及待地想试试看,OK写个控制台程序来测试一下:

static void Main(string[] args)
{
  EmployeeDetail employee = "Jackson.Bruce";
  Console.WriteLine("FirstName={0},MiddleNam={1},LastName={2}", employee.FirstName, employee.MiddleName, employee.LastName);
  Console.WriteLine("toString={0}", employee);
  Console.WriteLine();

  EmployeeCollection collection = "Michael.Jackson" + employee;

  collection += "Bruce.Lee";
  foreach (var e in collection)
  {
 Console.WriteLine(e);
  }
  Console.WriteLine();

  collection -= employee;

  foreach (var e in collection)
  {
 Console.WriteLine(e);
  }
  Console.WriteLine("===end===");
  Console.Read();
}

运行结果如下图所示:

全部代码,里面还包含其他运算符的重载,这里就不再介绍了,赶紧动手测试一下吧:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 重载运算符
{
  [Serializable]
  public class EmployeeDetail
  {
    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public string LastName { set;get; }
    public static EmployeeCollection operator +(EmployeeDetail a, EmployeeDetail b)
    {
      return new EmployeeCollection() { a, b };
    }

   
    
    public static EmployeeCollection operator +(EmployeeCollection collection, EmployeeDetail a)
    {
      collection.Add(a);
      return collection;
    }
    public static EmployeeCollection operator +(EmployeeDetail a, EmployeeCollection collection)
    {
      return collection + a;
    }
    /// <summary>
    /// 隐式类型转换
    /// </summary>
    /// <param name="name"></param>
    /// <returns></returns>
    public static implicit operator EmployeeDetail(string name)
    {
      string[] arr;
      return string.IsNullOrWhiteSpace(name) ? null :
        new EmployeeDetail()
        {
          FirstName = (arr = name.Trim().Split('.'))[0]
          ,
          LastName = arr.Length > 1 ? arr[arr.Length > 2 ? 2 : 1] : null,
          MiddleName = arr.Length > 2 ? arr[1] : null
        };
    }
    public static EmployeeCollection operator +(EmployeeDetail a, string b)
    {
      return new EmployeeCollection() { a, b };
    }
    public override string ToString()
    {
      return string.Format("{0}{1}{2}{3}{4}", FirstName, string.IsNullOrWhiteSpace(MiddleName) ? null : "."
        , MiddleName
        , string.IsNullOrWhiteSpace(LastName) ? null : ".",
        LastName).Trim();
    }
  }
  public class EmployeeCollection : List<EmployeeDetail>
  {
    public static EmployeeCollection operator +(EmployeeCollection a, string b)
    {
      a.Add(b);
      return a;
    }
    public static EmployeeCollection operator +(string b, EmployeeCollection a)
    {
      return a + b;
    }

    public static EmployeeCollection operator -(EmployeeCollection a, EmployeeDetail b)
    {
      a.Remove(b);
      return a;
    }
  }

  class Program
  {
    static void Main(string[] args)
    {
      EmployeeDetail employee = "Jackson.Bruce";
      Console.WriteLine("FirstName={0},MiddleNam={1},LastName={2}", employee.FirstName, employee.MiddleName, employee.LastName);
      Console.WriteLine("toString={0}", employee);
      Console.WriteLine();

      EmployeeCollection collection = "Michael.Jackson" + employee;

      collection += "Bruce.Lee";
      foreach (var e in collection)
      {
        Console.WriteLine(e);
      }
      Console.WriteLine();

      collection -= employee;

      foreach (var e in collection)
      {
        Console.WriteLine(e);
      }


      Console.WriteLine("===end===");
      Console.Read();
    }
  }
}

相关文章

  • C#使用AngleSharp库解析html文档

    C#使用AngleSharp库解析html文档

    这篇文章介绍了C#使用AngleSharp库解析html文档的方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-06-06
  • 一文带你了解C#操作MySql的方法

    一文带你了解C#操作MySql的方法

    工作中大多数情况下用的都是 MySql 但一直没有记录,相关操作。这篇文章以便 MySql.Data 库进行MySql操作,使用 C# 执行 SQL 语句,造个轮子
    2023-03-03
  • C#生成图形验证码的实现方式

    C#生成图形验证码的实现方式

    我们当用户登录系统时经常会用到图形验证码技术,要求用户识别图片中的内容,并正确输入,方可尝试登录,因此,图形验证码是一个网络安全技术手段,图形验证码的呈现形式有很多种,这里我们将介绍最基本的生成方式,感兴趣的朋友可以参考下
    2024-04-04
  • C#使用FileStream循环读取大文件数据的方法示例

    C#使用FileStream循环读取大文件数据的方法示例

    这篇文章主要介绍了C#使用FileStream循环读取大文件数据的方法,结合实例形式分析了FileStream文件流的形式循环读取大文件的相关操作技巧,需要的朋友可以参考下
    2017-05-05
  • 浅谈c# 面向对象之类与对象

    浅谈c# 面向对象之类与对象

    这篇文章主要介绍了c# 面向对象的类与对象的相关知识,非常的浅显易懂,有需要的小伙伴参考下。
    2014-12-12
  • unity3D实现物体任意角度自旋转

    unity3D实现物体任意角度自旋转

    这篇文章主要为大家详细介绍了unity3D实现物体任意角度自旋转,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2020-07-07
  • LZW压缩算法 C#源码

    LZW压缩算法 C#源码

    本文分享了一个LZW压缩算法的C#源码,有需要的朋友可以参考一下。
    2016-06-06
  • Unity实现UI渐隐渐显效果

    Unity实现UI渐隐渐显效果

    这篇文章主要为大家详细介绍了Unity实现UI渐隐渐显效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2020-04-04
  • c# linq的差集,并集,交集,去重代码(分享)

    c# linq的差集,并集,交集,去重代码(分享)

    下面小编就为大家分享一篇c# linq的差集,并集,交集,去重代码,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2017-11-11
  • c# 用ffmpeg从视频中截图

    c# 用ffmpeg从视频中截图

    这篇文章主要介绍了c# 用ffmpeg从视频中截图的方法,帮助大家更好的理解和学习使用c#,感兴趣的朋友可以了解下
    2021-03-03

最新评论