c# - 像c#中的指针一样吗?
问题描述
我是 c# 的新手(一般是和编码),我找不到任何等效的指针。
当我搜索谷歌时,我得到了安全/不安全之类的东西,但这不是我需要的。
就像在 c++ 中一样,如果你有一个指针并且它指向某个值,那么指针的变化会导致原始变量的变化。c#中有这样的东西吗?
例子-
static class universal
{
public static int a = 10;
}
class class_a
{
public void change1()
{
universal.a--;
}
}
class class_b
{
public void change2()
{
some_keyword temp = universal.a; //change in temp gives change in a
temp-= 5; //the purpose of temp is to NOT have to write universal.a each time
}
}
...
static void Main(string[] args)
{
class_b B = new class_b();
class_a A = new class_a();
A.change1();
Console.WriteLine(universal.a);//it will print 9
B.change2();
Console.WriteLine(universal.a);//it will print 4
Console.ReadKey();
}
编辑-谢谢@Sweeper,我得到了答案,我必须使用 ref int temp = ref universal.a;
解决方案
C#references
与指针非常相似。如果a
和b
都是对同一个对象的引用,那么在 中a
也会出现变化b
。
例如,在:
class X {
public int val;
}
void Main()
{
var a = new X();
var b = a;
a.val = 6;
Console.WriteLine(b.val);
}
6
将被写入。
如果您将X
from的声明更改class
为struct
,则a
andb
将不再是引用,并且0
将被写入。
推荐阅读
- generics - Kotlin 中的全局通用值
- regex - Sieve 给出的前面的正则表达式无效
- java - 在 GridLayout Android 中将图像拉伸到屏幕大小
- javascript - 我如何将 JsonString 日期与短日期进行比较
- java - 无法将管道分隔的标头数据解析为正确的变量
- sql - 聚合成默认值的更好方法
- python - 用另一列中的相同行值替换熊猫数据框列中的值
- wolfram-mathematica - Wolfram Mathematica 绘图错误怎么办
- java - Maven tomcat 依赖项未在 Eclipse 中下载;RSA premaster secret 错误
- python - dbt test的结果可以转换成report吗