Maf*_*fii 7 c# cil roslyn c#-6.0
当我输入这段代码时,我尝试使用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;
}
Run Code Online (Sandbox Code Playgroud)
它给了我这个代码:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我没有得到的是为什么它会在构造函数内部两次分配支持字段:
this.<x>k__BackingField = 5;
base(); // This is not valid C#, but it represents the IL correctly.
this.<x>k__BackingField = 4;.
Run Code Online (Sandbox Code Playgroud)
这是网站的错误还是Roslyn编译器实际上是这样做的(真是愚蠢的imo)?
我的意思是,如果我这样做
public C(int x)
{
this.x = x;
}
public int x { get; } = 5;
Run Code Online (Sandbox Code Playgroud)
并创建该代码:
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;
}
Run Code Online (Sandbox Code Playgroud)
但它不应该优化出来吗?
Man*_*mer 11
因为您在代码中设置了两次:
public C()
{
//here
x = 4;
}
//and here
public int x { get; } = 5;
Run Code Online (Sandbox Code Playgroud)
编辑问题后更新
但它不应该优化出来吗?
它可能,但只有当该类不从其构造函数中使用该值的另一个类继承时,它才知道它是一个自动属性,而setter不会做任何其他事情.
这将是很多(危险的)假设.在进行这样的优化之前,编译器需要检查很多东西.
原因是您在代码中设置了两次,无论是在属性声明中还是在构造函数中。
C# 6.0 只读属性
public int x { get; }
Run Code Online (Sandbox Code Playgroud)
其工作方式就像关于值分配的只读字段:您可以在构造函数中或声明的位置设置它。
编辑
多次初始化只读属性的一个示例是使用多个构造函数,其中只有一个构造函数重新定义您为该属性设置的“默认”值。
然而,就您而言,优化并不是一个坏主意,可能值得在Roslyn github 页面上将其作为功能请求提出
| 归档时间: |
|
| 查看次数: |
226 次 |
| 最近记录: |