匿名方法和匿名对象

简介: // Declare a delegate.delegate void Printer(string s);class TestClass{    static void Main()    {        // Instatiate the delegate type using an anonymous method.

// Declare a delegate.
delegate void Printer(string s);

class TestClass
{
    static void Main()
    {
        // Instatiate the delegate type using an anonymous method.
        Printer p = delegate(string j)
        {
            System.Console.WriteLine(j);
        };

        // Results from the anonymous delegate call.
        p("The delegate using the anonymous method is called.");

        // The delegate instantiation using a named method "DoWork".
        p = new Printer(TestClass.DoWork);

        // Results from the old style delegate call.
        p("The delegate using the named method is called.");
    }

    // The method associated with the named delegate.
    static void DoWork(string k)
    {
        System.Console.WriteLine(k);
    }
}
/* Output:
    The delegate using the anonymous method is called.
    The delegate using the named method is called.
*/


 

匿名对象

 

而在C# 3.0中,我们无须为这些无关紧要的类型浪费时间。通过使用“匿名类型”,只要在需要一个这样的对象时使用没有类型名字的new表达式。var b1 = new { Name = "The First Sample Book"Price = 88.0f };  

 
  1. var b2 = new { Price = 25.0f, Name = "The Second Sample Book" };  
  2. var b3 = new { Name = "The Third Sample Book"Price = 35.00f };  
  3.  
  4. Console.WriteLine(b1.GetType());  
  5. Console.WriteLine(b2.GetType());  
  6. Console.WriteLine(b3.GetType()); 


 

相关文章
|
2月前
|
C++
c++匿名对象
匿名对象 没有名字的对象。 这是一个自定义的类。
26 0
|
11月前
|
编译器
匿名对象与构造器
匿名对象与构造器
54 0
|
12月前
|
Java 编译器
构造函数中为什么要用this关键字?
构造函数中为什么要用this关键字?
51 0
|
编译器 C++
【C++】类和对象(中) —— 构造函数 | 析构函数 | 拷贝构造 | 赋值运算符重载【C++】类和对象(中) —— 构造函数 | 析构函数 | 拷贝构造 | 赋值运算符重载(下)
【C++】类和对象(中) —— 构造函数 | 析构函数 | 拷贝构造 | 赋值运算符重载【C++】类和对象(中) —— 构造函数 | 析构函数 | 拷贝构造 | 赋值运算符重载(下)
【C++】类和对象(中) —— 构造函数 | 析构函数 | 拷贝构造 | 赋值运算符重载【C++】类和对象(中) —— 构造函数 | 析构函数 | 拷贝构造 | 赋值运算符重载(下)
|
编译器 C++
【C++】类和对象(中) —— 构造函数 | 析构函数 | 拷贝构造 | 赋值运算符重载(上)
【C++】类和对象(中) —— 构造函数 | 析构函数 | 拷贝构造 | 赋值运算符重载(上)
【C++】类和对象(中) —— 构造函数 | 析构函数 | 拷贝构造 | 赋值运算符重载(上)
|
Java
Java中匿名子类 的 匿名对象、匿名子类 的 非匿名对象、非匿名类 的 匿名对象、非匿名类 的 非匿名对象
Java中匿名子类 的 匿名对象、匿名子类 的 非匿名对象、非匿名类 的 匿名对象、非匿名类 的 非匿名对象
200 0
|
程序员 C#
C# 匿名方法
每次写博客,第一句话都是这样的:程序员很苦逼,除了会写程序,还得会写博客!当然,希望将来的一天,某位老板看到此博客,给你的程序员职工加点薪资吧!因为程序员的世界除了苦逼就是沉默。我眼中的程序员大多都不爱说话,默默承受着编程的巨大压力,除了技术上的交流外,他们不愿意也不擅长和别人交流,更不乐意任何人走进他们的内心,他们常常一个人宅在家中! 废话说多了,咱进入正题: 上一节我们谈到了匿名变量,本节我们学习匿名方法。
915 0
|
C# 编译器
C# 匿名委托、匿名方法、匿名对象、Lambda表达式
原文:C# 匿名委托、匿名方法、匿名对象、Lambda表达式 一、匿名类型可通过使用 new 运算符和对象初始值创建匿名类型。示例:var v = new { Name = "Micro", Message = "Hello" };var v = new[] {     new { Name = "Micro", Message = "Hello" },     new { Name = "Soft", Message = "Wold!" }};匿名类型通常用在查询表达式的 select 子句中,以便返回源序列中每个对象的属性子集。
1669 0