相关疑难解决方法(0)

为什么你不能在成员初始化器中使用'this'?

可能重复:
在成员初始化程序中不能使用'this'?

如果我尝试做这样的事情,为什么我会收到错误的任何想法:

public class Bar
{
    public Bar(Foo foo)
    {
    }
}

public class Foo
{
    private Bar _bar = new Bar(this);
}
Run Code Online (Sandbox Code Playgroud)

我收到一个错误说:

"不能在成员初始化程序中使用'this'"

但以下工作:

public class Foo
{
    private Bar _bar;

    public Foo()
    {
        _bar = new Bar(this);
    }
}
Run Code Online (Sandbox Code Playgroud)

有谁知道这背后的原因?我的理解是这些会编译成同一个IL,所以很好奇为什么一个被允许而另一个不被允许.

谢谢,亚历克斯

c#

54
推荐指数
2
解决办法
4406
查看次数

在基础构造函数中使用lambdas表达式的例子

在我们构建的框架中,我们需要以下模式:

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)
     {}
}
Run Code Online (Sandbox Code Playgroud)

如您所见,我们在调用基础构造函数时创建了一个lambda.

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

奇怪的是,当尝试实际使用lambda时,它会抛出NullReferenceException(控制台应用程序)或某种ExecutionEngineExceptionexception(IIS上的Web应用程序).

我认为原因是在调用基础构造函数之前该指针尚未就绪,因此lambda this.Name在此阶段无法捕获.

它不应该在"捕获时间"而不是"执行时间"中抛出异常吗?这种行为是否有记录?

我可以用不同的方式重构代码,但我认为值得评论.

c# linq lambda c#-3.0

6
推荐指数
2
解决办法
889
查看次数

标签 统计

c# ×2

c#-3.0 ×1

lambda ×1

linq ×1