C#.NET使用operator重载操作符
业务需求:
在程序中要求将两个用户的用户名和他们的持有金额的相加,如何来实现呢?
一般实现如下:
- User user1 = new User();
- user1.Name = "张三";
- user1.Money = 20;
- User user2 = new User();
- user2.Name = "李四";
- user2.Money = 15;
- //将两个对象相加,得到用户名和金额合计
- User user3 = new User();
- user3.Name = user1.Name +","+ user2.Name;
- user3.Money = user1.Money + user2.Money;
- //打印结果:
- //user3.Name :“张三,李四”
- //user3.Moeny:“35”;
试想,能不能将user3那三行代码改为:
User user3 = user1 + user2;
或者说
User userSum = user1 + user2 + user3 + user4 + userN.....
------------------------------------------------------------------
如何实现这个“+”(加号操作符)的重载方法,让我们自己写的一些类型/对象之间可以进行用操作符来写,这样可以大量的简化一些代码。
在User类中的“+”(加号操作符)的重载方法如下:
- /// <summary>
- /// 将操作符+重载
- /// </summary>
- /// <param name="user1">用户1</param>
- /// <param name="user2">用户2</param>
- /// <returns></returns>
- public static User operator +(User user1, User user2)
- {
- User retUser = new User();
- retUser.Name = user1.Name +","+ user2.Name;
- retUser.Money = user1.Money + user2.Money;
- return retUser;
- }
完整Demo代码2个cs文件:
- //Main.cs
- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace OperatorDemo
- {
- class Program
- {
- static void Main(string[] args)
- {
- //创建对象“张三”
- User user_z = new User();
- user_z.Name = "张三";
- user_z.Money = 100;
- //创建对象“李四”
- User user_l = new User();
- user_l.Name = "李四";
- user_l.Money = 50;
- //将“张三”和“李四”相加
- User sumUser = user_z + user_l;
- //打印出相加后的结果
- Console.WriteLine("姓名:"+sumUser.Name);
- Console.WriteLine("持有金额:"+ sumUser.Money);
- Console.ReadLine();
- }
- }
- }
- //User.cs
- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace OperatorDemo
- {
- public sealed class User
- {
- /// <summary>
- /// 用户姓名
- /// </summary>
- public string Name { get; set; }
- /// <summary>
- /// 用户持有金额
- /// </summary>
- public decimal Money { get; set; }
- /// <summary>
- /// 将操作符+重载
- /// </summary>
- /// <param name="user1">用户1</param>
- /// <param name="user2">用户2</param>
- /// <returns></returns>
- public static User operator +(User user1, User user2)
- {
- User retUser = new User();
- retUser.Name = user1.Name +","+ user2.Name;
- retUser.Money = user1.Money + user2.Money;
- return retUser;
- }
- }
- }
以及操作可以写其他的操作符重载,比如 - * / == != > >= 等....
附上完整项目源码:http://files.cnblogs.com/andrew-blog/OperatorDemo.rar
http://115.com/file/c282b264
http://115.com/file/c28kpt6l#
《数据结构》课程个性化在线学习系统研究.doc