Are other commonly used framework structs such as DateTime
, TimeSpan
, Guid
, ... considered readonly
by the JIT?
- If this varies by platform, how can we find out which types are safe in a given situation?
推荐答案
快速测试表明,目前,是的,已为内置基本类型和结构创建了防御性副本.
A quick test shows that, currently, yes, a defensive copy is created for built-in primitive types and structs.
使用VS 2017(.NET 4.5.2,C#7.2,发布版本)编译以下代码:
Compiling the following code with VS 2017 (.NET 4.5.2, C# 7.2, release build):
using System;
class MyClass
{
public readonly struct Immutable { public readonly int I; public void SomeMethod() { } }
public struct Mutable { public int I; public void SomeMethod() { } }
public void Test(Immutable immutable, Mutable mutable, int i, DateTime dateTime)
{
InImmutable(immutable);
InMutable(mutable);
InInt32(i);
InDateTime(dateTime);
}
void InImmutable(in Immutable x) { x.SomeMethod(); }
void InMutable(in Mutable x) { x.SomeMethod(); }
void InInt32(in int x) { x.ToString(); }
void InDateTime(in DateTime x) { x.ToString(); }
public static void Main(string[] args) { }
}
使用ILSpy反编译时,
产生以下结果:
yields the following result when decompiled with ILSpy:
...
private void InImmutable([System.Runtime.CompilerServices.IsReadOnly] [In] ref MyClass.Immutable x)
{
x.SomeMethod();
}
private void InMutable([System.Runtime.CompilerServices.IsReadOnly] [In] ref MyClass.Mutable x)
{
MyClass.Mutable mutable = x;
mutable.SomeMethod();
}
private void InInt32([System.Runtime.CompilerServices.IsReadOnly] [In] ref int x)
{
int num = x;
num.ToString();
}
private void InDateTime([System.Runtime.CompilerServices.IsReadOnly] [In] ref DateTime x)
{
DateTime dateTime = x;
dateTime.ToString();
}
...
(或者,如果您更喜欢IL:)
(or, if you prefer IL:)
IL_0000: ldarg.1
IL_0001: ldobj [mscorlib]System.DateTime
IL_0006: stloc.0
IL_0007: ldloca.s 0
IL_0009: call instance string [mscorlib]System.DateTime::ToString()
IL_000e: pop
IL_000f: ret
这篇关于在修饰符中使用C#7.2处理具有原始类型的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!