
本文共 3265 字,大约阅读时间需要 10 分钟。
目录
匿名类型
匿名类型说明
匿名类型是没有名称的类,这一种方便的方法,可用将一组只读属性封装到单个对象中,而无需首先显式定义一个类型,类型名由编译器生成,并且不能在源代码级使用
也就是,匿名类实际上就是没有类型名称,其他地方与类是一样使用的。
匿名类示例
先看一个普通的类,具有三个变量和一个实例化函数,打印输出预先定义好的值
class student { public int Sub; int Age; int Cls; public student() { Console.WriteLine("Student A:{0}{1}{2}",Sub,Age,Cls); } }
在主函数中实例化
static void Main(string[] args) { student st = new student(); }
运行得到的结果:
那么如果用一个类似的匿名类来写,就是这样
static void Main(string[] args) { student st = new student(); var annoystudent = new { aSub = "DatAnalyse", aAge = 12, aCls = "Middle 4" }; Console.WriteLine("Data: {0}{1}{2}", annoystudent.aAge, annoystudent.aSub, annoystudent.aCls); }
为方便比较将两个写到一个程序中,全部代码如下
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace DelegateTest{ internal delegate void NumberChanger(int n); class student { public string Sub = "DatAnalyse"; private int Age = 12; private int Cls = 4; public student() { Console.WriteLine("Stand Student A:{0},{1},{2}",Sub,Age,Cls); Console.ReadKey(); } } class Program { static void Main(string[] args) { student st = new student(); var annoystudent = new { aSub = "DatAnalyse", aAge = 12, aCls = "Middle 4" }; Console.WriteLine("Annoy Student Data: {0},{1},{2}", annoystudent.aAge, annoystudent.aSub, annoystudent.aCls); Console.ReadKey(); } } }
编译运行,可以看到最终的结果与非匿名类是一样的
匿名类不能赋值,它的所有数值都是只读的
匿名方法
匿名方法说明
创建匿名方法实际上是一种将代码块作为委托参数传递的方式,使用这一种方法如果建立新的线程可以减少内存的消耗,匿名方法不声明返回值类型,但是匿名方法的返回值类型必须和委托返回值一样。
匿名方法示例
先定义一个普通的函数
static void TheMulti(int b) { var num = b * b; System.Console.WriteLine("{0}x{1} = {2}", b, b, b * b); }
之后定义一个delegate匿名函数的声明,其中参数类型与普通函数的是一致的,这一句我定义到了类的外面,因此增加一个internal声明
internal delegate void AutoCounter(int n);
主函数是这样的:
AutoCounter ac ; //实例化匿名方法AutoCounter ac = TheMulti; //赋予函数名称 ac(12); //调用 System.Console.ReadKey();
程序的运行结果与通常调用函数是一致的
另外直接声明匿名方法块也是可以的,
ac = delegate (int c)//声明 { var num = c + c; System.Console.WriteLine("{0}+{1} = {2}", c, c, (c + c)); }; ac(33);//调用
最终的函数如下:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace DelegateTest{ internal delegate void AutoCounter(int n); class Program { static void Main(string[] args) { AutoCounter ac ; ac = TheMulti; ac(12); ac = delegate (int c) { var num = c + c; System.Console.WriteLine("{0}+{1} = {2}", c, c, (c + c)); }; ac(33); System.Console.ReadKey(); } static void TheMulti(int b) { var num = b * b; System.Console.WriteLine("{0}x{1} = {2}", b, b, (b * b)); } } }
运行结果
发表评论
最新留言
关于作者
