码迷,mamicode.com
首页 > 其他好文 > 详细

C#中运算符重载

时间:2014-06-30 19:43:49      阅读:242      评论:0      收藏:0      [点我收藏+]

标签:style   blog   使用   strong   2014   cti   

很多语言都允许程序员使用运算符重载,尽管从编程的角度看,这没有其必要性,但是对于代码来讲可以提高它的可读性,带来许多方便之处。最简单的例子就是,我们用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#中运算符重载

标签:style   blog   使用   strong   2014   cti   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!