获取一个字符串以引用C#中的另一个

Ala*_*inD 11 c# string

我来自C++背景.之前已经问过这个问题,但试着尽可能找不到答案.比方说我有:

string[] ArrayOfReallyVeryLongStringNames = new string[500];
ArrayOfReallyVeryLongStringNames[439] = "Hello world!";
Run Code Online (Sandbox Code Playgroud)

我可以创建一个引用上面的字符串(这些都不会编译):

string a = ref ArrayOfReallyVeryLongStringNames[439];  // no compile
string a = &ArrayOfReallyVeryLongStringNames[439];     // no compile
Run Code Online (Sandbox Code Playgroud)

我确实理解字符串在C#中是不可变的.我也明白你无法获得托管对象的地址.

我想这样做:

a = "Donkey Kong";  // Now ArrayOfReallyVeryLongStringNames[439] = "Donkey Kong";
Run Code Online (Sandbox Code Playgroud)

我已经阅读了Stack Overflow问题在C#中引用了另一个字符串, 它有一个很好的答案,但问题略有不同.我不想通过引用将此参数传递给函数.我知道如何使用"ref"关键字通过引用传递参数.

如果答案是"您不能在C#中执行此操作",是否有方便的解决方法?

编辑:一些答案表明问题不清楚.让我们以不同的方式问它.假设我需要操纵原始长命名数组中具有主要索引的所有项目.我想在Array ... [2],Array ... [3],Array ... [5]等中添加别名到列表中.然后,使用"for"循环修改列表中的项目(可能通过将刚创建的列表传递给函数).

在C#中,"using"关键字为类或命名空间创建别名.从答案来看,似乎无法为变量创建别名.

Mat*_*son 12

您可以创建一个包装器来保持对底层数组的引用和字符串的索引:

public sealed class ArrayStringReference
{
    private readonly string[] _array;
    private readonly int      _index;

    public ArrayStringReference(string[] array, int index)
    {
        _array = array;
        _index = index;
    }

    public string Value
    {
        get
        {
            return _array[_index];
        }

        set
        {
            _array[_index] = value;
        }
    }

    public override string ToString()
    {
        return Value;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后这将工作:

    string[] ArrayOfReallyVeryLongStringNames = new string[500];
    ArrayOfReallyVeryLongStringNames[439] = "Hello world!";

    var strRef = new ArrayStringReference(ArrayOfReallyVeryLongStringNames, 439);
    Console.WriteLine(ArrayOfReallyVeryLongStringNames[439]); // Outputs "Hello world!"
    strRef.Value = "Donkey Kong";
    Console.WriteLine(ArrayOfReallyVeryLongStringNames[439]); // Outputs "Donkey Kong"
Run Code Online (Sandbox Code Playgroud)

您可以通过提供隐式字符串运算符使这更方便,因此您不必使用.Value访问基础字符串:

// Add this to class ArrayStringReference implementation

public static implicit operator string(ArrayStringReference strRef)
{
    return strRef.Value;
}
Run Code Online (Sandbox Code Playgroud)

然后,而不是像这样访问底层字符串:

strRef.Value = "Donkey Kong";
...
string someString = strRef.Value;
Run Code Online (Sandbox Code Playgroud)

你可以这样做:

strRef.Value = "Donkey Kong";
...
string someString = strRef; // Don't need .Value
Run Code Online (Sandbox Code Playgroud)

这只是语法糖,但它可能使开始使用ArrayStringReference现有代码更容易.(请注意,您仍然需要使用.Value设定基础字符串.)


Pat*_*man 5

你能得到的最接近的是:

unsafe
{
    string* a = &ArrayOfReallyVeryLongStringNames[439];     // no compile
}
Run Code Online (Sandbox Code Playgroud)

这给了一个例外:

不能获取地址,获取大小,或声明指向托管类型的指针('string')

所以不,不可能......

另请阅读此MSDN文章,该文章解释了可以使用的类型(blittable类型).