我用dnspy反编译了一些unity dll文件,得到了下面这行。
RuntimeHelpers.InitializeArray(array, fieldof(<PrivateImplementationDetails>.51A7A390CD6DE245186881400B18C9D822EFE240).FieldHandle);我需要了解这一行中的fieldof()函数我以前没有见过它(因为我是初学者)
以及它在该行中显示错误的两个原因
发布于 2020-04-04 17:44:31
在C#代码(和许多其他语言)编译成的中间语言MSIL中,有一个方便的fieldof操作符,它可以获取字段的FieldInfo。但是,C#中并不存在fieldof。
在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);发布于 2020-04-04 18:14:34
我建议从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; }
}因此,当您反编译具有此属性的类的程序集时,您将看到反编译器的输出完全像这样。
从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 ) 当您查看设置此属性的该类的构造函数IL时,您会看到它正在访问(backing)字段,如下所示:
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,最后,您在反编译器输出中看到的内容意味着,它只是设置了私有的自动生成字段。
https://stackoverflow.com/questions/61026150
复制相似问题