overload operator = in c#
Is it possible to overload operator = in c#?
when i call =, i just want to copy properties开发者_运维百科, rather than making the left hand reference to refer another instance.
The answer is no:
Note that the assignment operator itself (=) cannot be overloaded. An assignment always performs a simple bit-wise copy of a value into a variable.
And even if it was possible, I wouldn't recommend it. Nobody who reads the code is going to think that there's ANY possibility that the assignment operator's been overloaded. A method to copy the object will be much clearer.
You can't overload the =
operator. Furthermore, what you are trying to do would entirely change the operator's semantics, so in other words is a bad idea.
If you want to provide copy semantics, provide a Clone()
method.
Why not make a .CopyProperties(ByVal yourObject As YourObject) method in the object?
Are you using a built-in object?
We can Overload = operator but not directly.
using System;
class Over
{
private int a;
public Over(int a )
{
this.a = a;
}
public int A { get => a; }
public static implicit operator int(Over obj)
{
return obj.A;
}
}
class yo
{
public static void Main()
{
Over over = new Over(10);
int a = over;
}
}
Here when you call that operator overloading method , it is calling = operator itself to convert that to int. You cannot directly overload "=" but this way of code means the same.
精彩评论