当我输入这段代码时,我正在努力尝试
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上的功能请求提出可能是值得的