2

C# で文字列のような不変型へのポインターを格納する方法はありますか? 実行方法: Instance1.SomeFunction(out MyString);

、Instance1 内の MyString へのポインターを格納しますか?

4

4 に答える 4

0

このクラスをポインターとして使用します (注: テストされていないメモ帳のコードで、修正が必要な場合があります)。

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
于 2009-02-19T22:30:53.263 に答える
0

私はしばらくの間、C# でポインターと格闘してきましたが、オプションがないことに驚きました。C# でポインターとポインター引数を処理する場合、あらゆる種類のあいまいな障害に遭遇します。

  • 文字列でさえも、マネージド型へのネイティブ ポインターを作成することはできません。
  • 後で使用するために不変の out/ref-arguments を保存することはできません
  • 「null」が文字列型のデフォルト状態であっても、オプション/nullable の out/ref-arguments を持つことはできません
  • ラムダ式内で渡された/参照引数を使用することはできません

私が最近見つけたかなりきちんとした解決策と、この投稿の理由は次のとおりです。

void Test()
{
  string ret = "";
  SomeFunction(a=>ret=a);
}

void SomeFunction(string_ptr str)
{
   str("setting string value");
}

delegate void string_ptr(string a);
于 2009-02-19T20:04:02.287 に答える
0

質問者による回答に関して、何が問題なのですか:

class Program
{
    static void Main()
    {
        string str = "asdf";
        MakeNull(ref str);
        System.Diagnostics.Debug.Assert(str == null);
    }

    static void MakeNull(ref string s)
    {
        s = null;
    }

}
于 2009-02-19T23:00:05.160 に答える
0

わかりました、私の問題に対する別の部分的な解決策を見つけました。一部の ref/out-arguments に null 値を持たせたい場合は、オーバーロードを使用できます。

void Test()
{
    string ret1 = "", ret2 = "";
    SomeFunction(ref ret1, ref ret2);
    SomeFunction(null, ref ret2);
    SomeFunction(ref ret1, null);
    SomeFunction(null,null);
}

string null_string = "null";

void SomeFunction(ref string ret1,ref string ret2)
{
   if( ret1!=null_string )
       ret1 = "ret 1";
   if( ret2!=null_string )
       ret2 = "ret 2";
}

// Additional overloads, to support null ref arguments
void SomeFunction(string ret1,ref string ret2)
{
    Debug.Assert(ret1==null);
    SomeFunction(null_string,ret2);
}
void SomeFunction(ref string ret1,string ret2)
{
    Debug.Assert(ret2==null);
    SomeFunction(ret1,null_string);
}
void SomeFunction(string ret1,string ret2)
{
    Debug.Assert(ret1==null&&ret2==null);
    SomeFunction(null_string,null_string);
}
于 2009-02-28T10:31:08.850 に答える