首页 > 其他 > 详细

C#中运算符重载

时间:2014-06-30 19:44:18      阅读:321      评论:0      收藏:0      [点我收藏+]

很多语言都允许程序员使用运算符重载,尽管从编程的角度看,这没有其必要性,但是对于代码来讲可以提高它的可读性,带来许多方便之处。最简单的例子就是,我们用String类的时候,用“+”运算符直接实现字符串的连接,很方便很直观。

运算符重载实例:

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

namespace implicit隐式转换
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = 10;
	    Person p = n;	//隐式转换
            //Person p = (Person)n;	//显示转换
            Console.WriteLine(p.Age);
            Console.ReadKey();

        }
    }

    public class Person
    {
	//在此进行运算符重载  将传入的n赋值给Person对象的Age属性  
	//implicit隐式转换  explicit显示转换
        public static implicit operator Person(int n)
        {
            return new Person() { Age = n };
        }


        public string Name
        {
            get;
            set;
        }
        public int Age
        {
            get;
            set;
        }
        public string Email
        {
            get;
            set;
        }

    }
}

C#运算符重载的要求 运算符必须是 public 和 static 的,这是编译时的要求。

C#中运算符重载,布布扣,bubuko.com

C#中运算符重载

原文:http://blog.csdn.net/syaguang2006/article/details/35841323

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!