与C++不同,在C#中你不能重载赋值运算符。
我正在为进行大数运算的自定义Number类工作,并希望它具有内置数字类型(如int,decimal等)的外观和感觉。我已经重载了算术运算符,但是赋值运算符依然无法重载...
这里是一个例子:
Number a = new Number(55);
Number b = a; //I want to copy the value, not the reference
那个问题有没有解决的办法?
与C++不同,在C#中你不能重载赋值运算符。
我正在为进行大数运算的自定义Number类工作,并希望它具有内置数字类型(如int,decimal等)的外观和感觉。我已经重载了算术运算符,但是赋值运算符依然无法重载...
这里是一个例子:
Number a = new Number(55);
Number b = a; //I want to copy the value, not the reference
那个问题有没有解决的办法?
你可以使用“implicit”关键字来创建赋值的重载:
假设你有一个名为Foo的类型,你觉得它可以从字符串隐式转换。 你可以在Foo类中编写以下静态方法:
public static implicit operator Foo(string normalString)
{
//write your code here to go from string to Foo and return the new Foo.
}
完成这一步之后,您可以在代码中使用以下内容:
Foo x = "whatever";
我仍然不太清楚你是否真正需要它。 可以有两种选择:
或者:
你不能通过让C++代码看起来像C#来解决这个问题,因为在C++中,a = b; 的语义与在C#中不同。在C#中,a = b; 是将a指向与b相同的对象,而在C++中,a = b会改变a的内容。两者都有好处和坏处。这就像你做的事情一样。
MyType * a = new MyType();
MyType * b = new MyType();
a = b; /* only exchange pointers. will not change any content */
MyType a = new MyType();
MyType b = new MyType();
// instead of a = b
a.Assign(b);
免责声明: 我不是C#开发人员
你可以像这样创建一个只写属性。然后在上面执行 a.Self = b;
public MyType Self {
set {
/* copy content of value to this */
this.Assign(value);
}
}
在传递引用时,您可以使类成为不可变的,而不是复制数据。当类是不可变的时,拥有多个对它的引用并不是一个问题,因为它无法更改。
当更改数据的操作时,必须返回新的实例。
之前的帖子建议使用以下代码:
public static implicit operator Foo(string normalString) { }
我尝试了这种方法…但是要让它工作,你需要添加以下代码:
public static implicit operator Foo(Foo original) { }
而且编译器不允许你从自己的确切类型或任何基类型中拥有隐式转换函数。这是有道理的,因为这将是一种绕过赋值运算符的后门方式,而C#不想允许这种情况发生。
这是我自己使用的解决方案:
public class MyTestClass
{
private int a;
private string str;
public MyTestClass()
{
a = 0;
str = null;
}
public MyTestClass(int a, string str)
{
this.a = a;
this.str = str;
}
public MyTestClass Clone
{
get
{
return new MyTestClass(this.a, this.str);
}
}
}
在代码的其他地方:
MyTestClass test1 = new MyTestClass(5, "Cat");
MyTestClass test2 = test1.Clone;