相当于Java的C#固定关键字

问题描述 投票:0回答:1

我想防止垃圾收集器重新定位移动变量。我需要设置一个指向托管变量的指针(我要创建一个指针),并在执行过程中“锚定”该变量。

换句话说,如何将C#代码转换为Java?:

fixed (Char* sPtr = s) {
    //s = any String variable
    return convertToSomething(sPtr, s.Length); //Any method
}
java c# fixed
1个回答
0
投票
String s = ...; return convertToSomething(s, s.length());

如果s是多线程环境中的实例变量,那么您可以简单地将引用“复制”到您的方法中:

private volatile String s; // should be volatile, else you may work with stale references

public Something yourMethod() {
    String sLocal = s; // copy the reference, sLocal will be the value of s at the time the method was invoked
    return convertToSomething(sLocal, sLocal.length());
}

也可以看看Is Java "pass-by-reference" or "pass-by-value"

© www.soinside.com 2019 - 2024. All rights reserved.