C# 高级编程 里面的委托例子。

本文介绍了一个使用C#实现的货币类的设计方法,包括显示格式化、浮点数到货币类型的转换以及货币类型到浮点数的转换。此外还展示了如何通过委托来调用类的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace ConsoleApplication1

{

    public class Currency

    {

        public uint Dollars;

        public ushort Cents;

 

        public Currency()

        {

 

        }

        public Currency(uint dollars,ushort cents)

        {

            this.Dollars = dollars;

            this.Cents = cents;

 

        }

        public override string ToString()

        {

            return string.Format("{0:c}.{1,-2:00}", Dollars, Cents);

        }

        public static string GetCurrencyUint()

        {

            return "人民币";

        }

        public static explicit operator Currency(float value)

        {

            checked

            {

                uint dollars = (uint)value;

                ushort cents =(ushort) ((value - dollars)*100);

                return new Currency(dollars, cents);

            }

        }

        public static implicit operator float(Currency value)

        {

            return value.Dollars + value.Cents / 100.0f;

 

        }

        public static implicit operator Currency(uint value)

        {

            return new Currency(value, 0);

        }

        public static implicit operator uint(Currency value)

        {

            return value.Dollars;

        }

    }

    delegate string GetAString();

    

    class Program

    {

        static void Main(string[] args)

        {

            int x = 40;

            GetAString firstStringMethod = x.ToString;

            Console.WriteLine("String is {0}",firstStringMethod());

         

 

            Currency balance = new Currency(34, 50);

 

            firstStringMethod = balance.ToString;

 

            Console.WriteLine("String is {0}", firstStringMethod());

 

            firstStringMethod = new GetAString(Currency.GetCurrencyUint);

            Console.WriteLine("String is {0}",firstStringMethod());

        }

    }

}

 

//

 // /* 以下是运行的结果. String is 40 String is ¥34.50 String is 人民币请按任意键继续. . . */

转载于:https://www.cnblogs.com/fat_li/archive/2010/10/28/1863315.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值