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

前端之家收集整理的这篇文章主要介绍了c# – 为什么IL将此值设置两次?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
当我输入这段代码时,我正在努力尝试 Try Roslyn
  1. using System;
  2. using System.Linq;
  3. using System.Collections.Generic;
  4. using Microsoft.CSharp;
  5.  
  6. public class C {
  7.  
  8. public C()
  9. {
  10. x = 4;
  11. }
  12.  
  13. public int x { get; } = 5;
  14. }

它给了我这个代码

  1. using System;
  2. using System.Diagnostics;
  3. using System.Reflection;
  4. using System.Runtime.CompilerServices;
  5. using System.Security;
  6. using System.Security.Permissions;
  7. [assembly: AssemblyVersion("0.0.0.0")]
  8. [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
  9. [assembly: CompilationRelaxations(8)]
  10. [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
  11. [assembly: SecurityPermission(SecurityAction.RequestMinimum,SkipVerification = true)]
  12. [module: UnverifiableCode]
  13. public class C
  14. {
  15. [DebuggerBrowsable(DebuggerBrowsableState.Never),CompilerGenerated]
  16. private readonly int <x>k__BackingField;
  17. public int x
  18. {
  19. [CompilerGenerated]
  20. get
  21. {
  22. return this.<x>k__BackingField;
  23. }
  24. }
  25. public C()
  26. {
  27. this.<x>k__BackingField = 5;
  28. base(); // This is not valid C#,but it represents the IL correctly.
  29.  
  30. this.<x>k__BackingField = 4;
  31. }
  32. }

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

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

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

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

  1. public C(int x)
  2. {
  3. this.x = x;
  4. }
  5.  
  6. public int x { get; } = 5;

并创建该代码

  1. public C(int x)
  2. {
  3. this.<x>k__BackingField = 5;
  4. base(); // This is not valid C#,but it represents the IL correctly.
  5.  
  6. this.<x>k__BackingField = x;
  7. }

但它不应该优化出来吗?

解决方法

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

C#6.0只读属性

  1. public int x { get; }

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

编辑

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

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

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

猜你在找的C#相关文章