首页 技术 正文
技术 2022年11月9日
0 收藏 851 点赞 2,483 浏览 1484 个字

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

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

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

示例代码:

/*
* 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) * );
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, );
}
//隐式转换 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 = ;
//委托推断 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(, ); //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();
}
}
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,498
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,911
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,745
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,501
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,140
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,303