Is there a workaround for overloading the assignme

2019-01-21 11:07发布

Unlike C++, in C# you can't overload the assignment operator.

I'm doing a custom Number class for arithmetic operations with very large numbers and I want it to have the look-and-feel of the built-in numerical types like int, decimal, etc. I've overloaded the arithmetic operators, but the assignment remains...

Here's an example:

Number a = new Number(55); 
Number b = a; //I want to copy the value, not the reference

Is there a workaround for that issue?

7条回答
仙女界的扛把子
2楼-- · 2019-01-21 11:29

An earlier post suggested this:

public static implicit operator Foo(string normalString) { }

I tried this approach... but to make it work you need this:

public static implicit operator Foo(Foo original) { }

and the compiler won't let you have an implicit conversion function from your exact type, nor from any base type of yourself. That makes sense since it would be a backdoor way of overriding the assignment operator, which C# doesn't want to allow.

查看更多
登录 后发表回答