有没有办法在 C# 中存储指向不可变类型(如字符串)的指针? 如何执行: Instance1.SomeFunction(out MyString);
,并在 Instance1 中存储指向 MyString 的指针?
最佳答案
使用此类作为指针(注意:未经测试的记事本代码,可能需要一些修复):
public class Box<T> {
public Box(T value) { this.Value = value; }
public T Value { get; set; }
public static implicit operator T(Box<T> box) {
return box.Value;
}
}
例如,
public void Test() {
Box<int> number = new Box<int>(10);
Box<string> text = new Box<string>("PRINT \"Hello, world!\"");
Console.Write(number);
Console.Write(" ");
Console.WriteLine(text);
F1(number, text);
Console.Write(number);
Console.Write(" ");
Console.WriteLine(text);
Console.ReadKey();
}
void F1(Box<int> number, Box<string> text) {
number.Value = 10;
text.Value = "GOTO 10";
}
应该输出
10 PRINT "Hello, world!"
20 GOTO 10
关于c# - 在 C# 中传递和存储指向不可变类型和字符串的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/566908/