作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我能够在其(实例)方法之外获取结构的地址,如下所示:
public struct Values
{
public byte A;
public byte B;
public byte C;
public byte D;
public static unsafe bool Equals(Values lhs, Values rhs)
{
return *(int*) &lhs == *(int*) &rhs;
}
}
但是当我尝试获取结构本身的地址时,IDE 告诉我这是错误的:
public unsafe bool Equals(Values other)
{
return *(int*) &this == *(int*) &other;
}
错误信息是:
You can only take the address of an unfixed expression inside of a fixed statement initializer.
fixed 语句防止垃圾收集器重定位可移动变量。但是这个结构不是可移动变量,不会被垃圾回收,对吧?
已更新
我实际需要的是通过索引获取/设置第 N 个字节的值。虽然我可以通过 switch 语句来完成,但是通过索引会更快。感谢@KonradKokosa,Fixed Size Buffer满足我的需求。我仍然想知道主要问题的答案。
最佳答案
您不能在结构实例方法中获取 this
的地址,因为 “this struct is not a movable variable” 不是真实的陈述。结构可以装箱,因此它立即变得可移动。实例方法不知道它是从装箱结构还是非装箱结构中调用的。
请注意,它目前也是 ref struct
的长期限制,尽管它可以解除。所以,下面的代码仍然会产生相同的编译错误:
public ref struct C {
public void M() {
var ptr = &this;
}
}
但是,您可以在第一个片段中获取结构的地址:
public static unsafe bool Equals(Values lhs, Values rhs)
{
return *(int*) &lhs == *(int*) &rhs;
}
因为您在这里获取局部参数的地址,按值传递(最后是 Values
的副本)。
关于c# - 如何在其方法中获取结构的地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64112247/
我是一名优秀的程序员,十分优秀!