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

Csharp 高级编程 C7.1.2(2)

时间:2014-05-09 10:05:12      阅读:282      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   java   ext   

C#2.0  使用委托推断扩展委托的语法
下面是示例  一个货币结构

代理的方法可以是实例的方法,也可以是静态方法,声明方法不同

实例方法可以使用委托推断,静态方法不可以用

示例代码:

bubuko.com,布布扣
/*
 * C#2.0  使用委托推断扩展委托的语法
 * 下面是示例  一个货币结构
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace C7._1._2_2
{
    //一个货币结构
    struct Currency 
    {
        //美元
        public uint Dollars;
        //美分
        public ushort Cents;
        //构造函数
        public Currency(uint dollars, ushort cents)
        {
            this.Dollars = dollars;
            this.Cents = cents;
        }
        //重写TOSTRING方法
        public override string ToString()
        {
            return string.Format("${0}.{1,-2:00}", Dollars, Cents);
        }
        //静态方法
        public static string GetCurrencyUnit()
        {
            return "Dollars";
        }
        //强制转换float -> Currency
        public static explicit operator Currency(float value)
        {
            checked {
                uint dollars = (uint)value;
                ushort cents = (ushort)((value - dollars) * 100);
                return new Currency(dollars, cents);
            }
        }
        //隐式转换 Currency -> float
        public static implicit operator float(Currency value)
        {
            return value.Dollars + (value.Cents / 100.0f);
        }
        //隐式转换 uint -> Currency
        public static implicit operator Currency(uint value)
        {
            return new Currency(value, 0);
        }
        //隐式转换 Currency -> uint
        public static implicit operator uint(Currency value)
        {
            return value.Dollars;
        }
    }
    class Program
    {
        private delegate string GetAString();

        static void Main(string[] args)
        {
            int x = 10;
            //委托推断  GetAString test = new GetAString(x.ToString);    C#2.0以后可以这样
            GetAString test = x.ToString;   
            Console.WriteLine("Get the string is {0}", test());

            Currency balance = new Currency(34, 50);
            
            //TEST 指向的是一个实例方法
            test = balance.ToString;
            Console.WriteLine("Get the string is {0}", test());

            //TEST指向的是一个静态方法注意声明方法不一样,不可以使用委托推断
       test = new GetAString(Currency.GetCurrencyUnit); Console.WriteLine("Get the string is {0}", test()); Console.ReadLine(); } } }
bubuko.com,布布扣

 

Csharp 高级编程 C7.1.2(2),布布扣,bubuko.com

Csharp 高级编程 C7.1.2(2)

标签:style   blog   class   code   java   ext   

原文地址:http://www.cnblogs.com/aocshallo/p/3716882.html

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