c# - 在 C# 中传递和存储指向不可变类型和字符串的指针

标签 c# function pointers arguments immutability

有没有办法在 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/

相关文章:

c# - 我这种设计WPF UI的方法对吗?

c# - 无法隐式转换类型 System.Collections.Generic.Dictionary<System.Tuple<int,int,string>, AnonymousType#1>

function - 为什么在生产环境下运行时,我无法在实时服务器上调用 Coldfusion CFC 中的函数?

c - 查找字符串中最常见的一对字符

c++ - 如何正确从函数返回指针

c - C 中的列表实现

C# Linq 语句或用于总计子集的 foreach()?

c# - 具有大量数据的客户端缓存 DropDownList?

javascript - boolean 值不是函数

C - 初始化结构中的指针