c# – 为什么IL将此值设置两次?

当我输入这段代码时,我正在努力尝试 Try Roslyn
using System;
using System.Linq;
using System.Collections.Generic;
using Microsoft.CSharp;

public class C {

    public C()
    {
        x = 4;
    }

    public int x { get; } = 5;
}

它给了我这个代码

using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;
using System.Security.Permissions;
[assembly: AssemblyVersion("0.0.0.0")]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.disableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum,SkipVerification = true)]
[module: UnverifiableCode]
public class C
{
    [Debuggerbrowsable(DebuggerbrowsableState.Never),CompilerGenerated]
    private readonly int <x>k__backingField;
    public int x
    {
        [CompilerGenerated]
        get
        {
            return this.<x>k__backingField;
        }
    }
    public C()
    {
        this.<x>k__backingField = 5;
        base(); // This is not valid C#,but it represents the IL correctly.

        this.<x>k__backingField = 4;
    }
}

我没有得到的是为什么它会在构造函数中两次分配支持字段:

this.<x>k__backingField = 5;
        base(); // This is not valid C#,but it represents the IL correctly.

        this.<x>k__backingField = 4;.

这是网站的错误还是Roslyn编译器实际上是这样做的(真是愚蠢的imo)?

我的意思是,如果我这样做

public C(int x)
 {
   this.x = x;
 }

public int x { get; } = 5;

并创建该代码

public C(int x)
{
    this.<x>k__backingField = 5;
    base(); // This is not valid C#,but it represents the IL correctly.

    this.<x>k__backingField = x;
}

但它不应该优化出来吗?

解决方法

原因是您在代码中设置了两次,无论是在属性声明中还是在构造函数中.

C#6.0只读属性

public int x { get; }

就像关于值赋值的只读字段一样工作:您可以在构造函数中或在声明的位置设置它.

编辑

>这个问题有两个部分:第一,当前
http://tryroslyn.azurewebsites.net/(截至2016.05.25)编译
DEBUG模式下的代码,即使在.中选择了Release选项
页面标题.
>其次罗斯林真的没有优化出来
readonly属性的双重声明,所以如果你使用VS15和
在发布模式下编译此代码,x将被分配两次

使用多次初始化readonly属性的示例可以是多个构造函数的使用,其中只有一个重新定义为属性设置的“认”值.

但是在您的情况下,优化并不是一个坏主意,因此将其作为Roslyn github page上的功能请求提出可能是值得的

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...