什么是 C# 中的 "fieldof()" 方法

what is "fieldof()" method in c#

我在dnspy中反编译了一些unity dll文件 得到这条线

RuntimeHelpers.InitializeArray(array, fieldof(<PrivateImplementationDetails>.51A7A390CD6DE245186881400B18C9D822EFE240).FieldHandle);

我需要了解该行中的 fieldof() 函数,我以前从未见过它(因为我是初学者)

以及在该行中显示错误的两个原因

在 MSIL 中,C# 代码(和许多其他语言)被编译成的中间语言,有这个方便的 fieldof 运算符可以获取字段的 FieldInfo。但是,fieldof 在 C# 中不存在。

在 C# 中,您需要执行如下操作:

var type = typeof(EnclosingClass); // "EnclosingClass" is the class this code is in
// assuming PrivateImplementationDetails is private
var fieldInfo = type.GetField("PrivateImplementationDetails", BindingFlags.NonPublic);
RuntimeHelpers.InitializeArray(array, fieldInfo.FieldHandle);

我建议从 C# 8.0 开始阅读以下内容,以了解每个版本的 C# 中的新功能。

https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8

在早期,我们习惯于实现如下属性:

private string userName;
public string UserName
{
    get { return userName; }
    set { userName = value; }
}

因此,当您使用此 属性 反编译具有 class 的程序集时,您会看到与此完全相同的反编译器输出。

自从 C# 2.0 以来,一直在不断改进,现在有多种在 C# 中实现属性的方法。

public string StringProperty1 => "String Property Value";

public string StringProperty2 { get; private set; }

public ICollection<double> Grades { get; } = new List<double>();

这里有什么共同点?

它们没有可供读取或写入的字段。此类声明的字段由编译器创建并存储在名为 PrivateImplementationDetails 的结构中。这不一定是一个独立的领域。这只是运行时访问属性的自动生成的私有支持字段的方式。

例如,对于名称为 AProperty 的 int[] 属性,将生成以下 IL:

.field private int32[] '<AProperty>k__BackingField'
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) 

并且当您查看此 class 的构造函数 IL 并设置此 属性 时,您会看到它正在像这样访问(支持)字段:

  IL_0009:  ldc.i4.3
  IL_000a:  newarr     [mscorlib]System.Int32
  IL_000f:  dup
  IL_0010:  ldtoken    field valuetype '<PrivateImplementationDetails>{3CA49917-EFBC-4E01-A884-1CFF6283A97C}'/'__StaticArrayInitTypeSize=12' '<PrivateImplementationDetails>{3CA49917-EFBC-4E01-A884-1CFF6283A97C}'::'$$method0x6000029-1'
  IL_0015:  call       void [mscorlib]System.Runtime.CompilerServices.RuntimeHelpers::InitializeArray(class [mscorlib]System.Array,

最后,您在反编译器输出中看到的意思是,它正在设置自动生成的私有字段。