匿名类型与扩展方法

匿名类型

匿名类型就是没有名字的类型。在C#3.0中允许我们在程序中声明一个临时的类型来存储数据,例如:

var noname = new { name = "Jerry", age = 10 };

编译器编译后的反编译出来的代码为:

View Code
[DebuggerDisplay(@"\{ name = {name}, age = {age} }", Type="<Anonymous Type>"), CompilerGenerated]
internal sealed class <>f__AnonymousType0<<name>j__TPar, <age>j__TPar>
{
    // Fields
    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
    private readonly <age>j__TPar <age>i__Field;
    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
    private readonly <name>j__TPar <name>i__Field;

    // Methods
    [DebuggerHidden]
    public <>f__AnonymousType0(<name>j__TPar name, <age>j__TPar age);
    [DebuggerHidden]
    public override bool Equals(object value);
    [DebuggerHidden]
    public override int GetHashCode();
    [DebuggerHidden]
    public override string ToString();

    // Properties
    public <age>j__TPar age { get; }
    public <name>j__TPar name { get; }
}

其实就是用对象初始化器的做法初始化一个属性都为只读的匿名类型。

在MSDN 中匿名类型的定义是这样的:

   1.匿名类型提供了一种方便的方法,可用来将一组只读属性封装到单个对象中,而无需首先显式定义一个类型。

   2.类型名由编译器生成,并且不能在源代码级使用。每个属性的类型由编译器推断。

   3.可通过使用 new 运算符和对象初始值创建匿名类型。

可通过将隐式键入的本地变量与隐式键入的数组相结合创建匿名键入的元素的数组,如下面的示例所示。

 var anonArray = new[] { new { name = "apple", diam = 4 }, new { name = "grape", diam = 1 }};

扩展方法

View Code
 public class Student
    {
        public int Age { get; set; }
    }
    public static class ExtendMethods
    {
        public static string Hello(this Student stu)
        {
            return "hello extend method" + stu.Age;
        }
    }

 static void Main()
        {
            Student stu = new Student { Age = 10 };
            Console.WriteLine(stu.Hello());
        }

如上例所示,即为Student类增加了一个Hello的扩展方法,效果等同于在Student类中增加了一个静态方法,但该方法只能访问Student类中的公共变量,常用于给第三方库扩展方法。

原文地址:https://www.cnblogs.com/Finding2013/p/3014892.html