角落的情况下,在基类的构造使用lambda表达式表达 [英] Corner case in using lambdas expression in base constructor

查看:108
本文介绍了角落的情况下,在基类的构造使用lambda表达式表达的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我们正在建立我们需要以下模式的框架:

In the Framework we are building we need the following pattern:

public class BaseRenderer
{
    Func<string> renderer;
    public BaseRenderer(Func<string> renderer)
    {
        this.renderer = renderer;
    }

    public string Render()
    {
        return renderer();
    }
}

public class NameRenderer : BaseRenderer
{
    public string Name{ get; set; }

     public NameRenderer ()
        : base(() =>this.Name)
     {}
}

如你所见,我们调用基构造函数时创建一个lambda。

As you see, we create a lambda when calling the base constructor.

public class Program
{
    public static void Main()
    {
        Console.WriteLine(new NameRenderer(){Name = "Foo"}.Render());
    }
}



奇怪的是,试图真正使用它抛出拉姆达时的NullReferenceException(控制台应用程序),或某种ExecutionEngineExceptionexception的(在IIS的Web应用程序)。

Oddly, when trying to actually use the lambda it throws NullReferenceException (Console Application), or some kind of ExecutionEngineExceptionexception (Web app on IIS).

我想原因是,这个指针不调用基类的构造前准备好,所以拉姆达是无法捕捉 this.Name 在这个阶段。

I think the reason is that this pointer is not ready before calling base constructor, so the lambda is unable to capture this.Name at this stage.

难道不应该扔在捕获时间,而不是执行时间例外吗?
是这种行为记录?

Shouldn't it throw an exception in "capture time" instead of "execution time"? Is this behavior documented?

我可以重构以不同的方式代码,但我认为这一点,实在值得评论。

I can refactor the code in a different way, but I think it worths a comment.

推荐答案

由于asgerhallas正确地指出,这应该根据规范不合法。我们无意让这个虚假的使用由搜索不正确的用法本之前,它是合法的,这样做的错误检测器潜行。我已经解决了的bug;在C#编译器4正确标记你的程序是一个错误。

As asgerhallas correctly points out, this should not be legal according to the specification. We accidentally allowed this bogus usage to sneak by the error detector that searches for incorrect usages of "this" before it is legal to do so. I've fixed the bug; the C# 4 compiler correctly flags your program as an error.

带来的不便表示歉意很多;这是我的错误。

Many apologies for the inconvenience; this was my mistake.

这篇关于角落的情况下,在基类的构造使用lambda表达式表达的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆