C# で文字列のような不変型へのポインターを格納する方法はありますか? 実行方法: Instance1.SomeFunction(out MyString);
、Instance1 内の MyString へのポインターを格納しますか?
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# でポインターとポインター引数を処理する場合、あらゆる種類のあいまいな障害に遭遇します。
私が最近見つけたかなりきちんとした解決策と、この投稿の理由は次のとおりです。
void Test()
{
string ret = "";
SomeFunction(a=>ret=a);
}
void SomeFunction(string_ptr str)
{
str("setting string value");
}
delegate void string_ptr(string a);
質問者による回答に関して、何が問題なのですか:
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;
}
}
わかりました、私の問題に対する別の部分的な解決策を見つけました。一部の 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);
}