加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 08:09:18 所属栏目:百科 来源:网络整理
导读:当我输入这段代码时,我正在努力尝试 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
当我输入这段代码时,我正在努力尝试 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上的功能请求提出可能是值得的

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读