FreeOZ论坛

标题: C#笔试问题 [打印本页]

作者: xyouc    时间: 9-12-2009 09:58
标题: C#笔试问题
请说明如下代码中的this的意义。

public static class StreamReaderExtensions
{
    public static IEnumerable<string> Lines(this StreamReader reader)
    {
        if (reader== null)
            throw new ArgumentNullException("reader");
        reader.BaseStream.Seek(0, SeekOrigin.Begin);
        string line;
        while ((line = reader.ReadLine()) != null)
            yield return line;
    }
}

把我难住了。

那位大虾讲讲啊?说实话,这个好像讲yield return的迭代的,以前基本没用过这个,嘿嘿。不知道代码里的"this"是啥意思。

形参里面为啥多一个this呢?

这个静态类的静态方法好像之需要申明 StreamReader 就可以使用了,为什么不StreamReaderExtensions.Lines(sr)来调用呢?

发现自己用了很多年c#,已经跟不上了,因为我的知识好像还停留在c# 1.0时代。

多谢!
作者: workinvm    时间: 9-12-2009 10:12
这是对 StreamReader 的扩展方法,也就是说为 StreamReader 这个类扩展一个 Lines 方法。这是 .net 3.0 的新特性。
参见
http://msdn.microsoft.com/en-us/library/bb383977.aspx

[ 本帖最后由 workinvm 于 9-12-2009 10:15 编辑 ]
作者: xyouc    时间: 9-12-2009 10:20
看来是时间研究一下c# 3.0的新特性了。
作者: workinvm    时间: 9-12-2009 10:27
C# 2.0 比 C#1.1 多了很多东西,C#3.0 又比 C#2.0多了很多 ,C#3.5 又多了很多,现在已经 C#4.0了,学习速度赶不上框架升级速度。
作者: wancyzhang    时间: 9-12-2009 11:06
这个this 是对StreamReader 的扩展,也就是说在这个程序中,所有StreamReader 类都将拥有Lines这个方法。
好像是3.0才出来的新特性
作者: procoder    时间: 9-12-2009 13:19
this 就是StreamReader。用到Visitor pattern。




欢迎光临 FreeOZ论坛 (https://www.freeoz.org/ibbs/) Powered by Discuz! X3.2