gpt4 book ai didi

c# - 是否有等同于 FormatterServices.GetUninitializedObject() 的表达式树?

转载 作者:行者123 更新时间:2023-11-30 17:45:05 31 4
gpt4 key购买 nike

通常我会调用 Expression.New(type),但是当类型没有无参数构造函数时,这是不可能的。

  • FormatterServices.GetUninitializedObject() 在内部如何工作?
  • 调用 operator new() 是否比调用 FormatterServices.GetUninitializeObject() 更快?
  • 是否有与 GetUninitializedObject 等效的 Expressions,或者唯一的方法是使用 Expression.Call

最佳答案

来自 MSDN :

Because the new instance of the object is initialized to zero and no constructors are run, the object might not represent a state that is regarded as valid by that object. The current method should only be used for deserialization when the user intends to immediately populate all fields. It does not create an uninitialized string, since creating an empty instance of an immutable type serves no purpose.

所以,回答你的问题:

  1. 我查看了使用 ILSpy 的方法,它所做的只是一些检查,然后调用 native (我假设是 C++)方法。我猜它只是为对象分配了足够的内存,将所有字段初始化为零/空,然后返回指向该对象的指针。没有构造函数被调用。
  2. 假设 new() 构造函数什么都不做,它们可能大致相同。
  3. 没有。你必须使用 Expression.Call,它会返回一个 object 然后如果你想用它做任何事情 Expression.Convert 到任何类型你需要这个对象。

关于c# - 是否有等同于 FormatterServices.GetUninitializedObject() 的表达式树?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28470229/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com