Der folgende Code hat ein Laufzeitproblem mit unerwarteten Verweisen durch Zuweisung von Postfix/Präfix Inkrementanweisung wie im folgenden Code gezeigt. Kann mir jemand bitte einen Weg vorschlagen, Objekte als Werttypen in C# zu behandeln, wie es unter anderem vorgeschlagen wird?Präfix und Postfix-Operator überladen in C#
Ich glaube, dass der Code gut dokumentiert ist mit Kommentaren jeden wichtigen Zustand zu klären. Fühlen Sie sich frei, irgendwelche Fragen bezüglich der Klärung des Codes oder des vorliegenden Problems zu stellen.
Vielen Dank im Voraus.
class Test {
public int x;
public Test(int x) { this.x=x; }
public Test() { x=0; }
static public Test operator++(Test obj) {
return new Test(obj.x+1);
}
}
// In implementing module
// Prefix/Postfix operator test for inbuilt (scalar) datatype 'int'
int x=2;
int y=++x; // 'y' and 'x' now both have value '3'
Console.WriteLine(x++); // Displays '3'
Console.WriteLine(++x); // Displays '5'
Console.WriteLine(ReferenceEquals(x,y)); // Displays 'False'
// Prefix/Postfix operator test of class type 'Test'
Test obj=new Test();
obj.x=1;
Console.WriteLine(obj++); // Must have displayed '1', displays the object type (Test.Test)
Console.WriteLine(++obj); // Must have displayed '3', again displays the object type (Test.Test)
Console.WriteLine(obj.x); // Displays '3' (as expected)
Test obj2=++obj; // Must have the value '4' and must NOT be the reference of obj
// Alternative solution to the above statement can be : 'Test obj2=new Test(++obj);' but isn't there a way to create a new value type in C# by the above statement ??!! (In C++, it can be acheived by overloading the '=' operator but C# doesn't allow it)
Console.WriteLine(obj2.x); // Displays '4' (as expected)
Console.WriteLine(ReferenceEquals(obj,obj2)); // Must display 'False' but displays 'True' showing that 'obj2' is the reference of 'obj'
Nun ja, Sie haben 'ToString()' nicht überschrieben. An diesem Punkt geht die Hälfte Ihrer Einwände weg. Es würde wirklich helfen, wenn du ein [mcve] schreibst, das ein * single * Problem demonstriert. –
@ user3185569: Ich habe dieses Bit des Kommentars entfernt. Es sieht für mich so aus, als ob der Teil über 'obj' und' obj2' in Ordnung sein sollte ... Es hilft nicht, dass es hier so viele zusammenhängende Probleme gibt. –
Eigentlich nein, ich sehe, was mit dem 'Test obj2 = ++ obj' Teil falsch ist. Wird eine Antwort dafür hinzufügen. –