C# 中的重载运算符 =

发布于 2024-08-15 02:25:50 字数 65 浏览 6 评论 0原文

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

救赎№ 2024-08-22 02:25:50

答案是

请注意,赋值运算符本身 (=) 不能被重载。赋值总是将值执行简单的按位复制到变量中。

即使可能,我也不会推荐它。阅读代码的人不会认为赋值运算符有可能被重载。有了复制对象的方法就会清晰很多。

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.

甜味超标? 2024-08-22 02:25:50

您不能重载 = 运算符。此外,您尝试做的事情将完全改变运算符的语义,因此换句话说这是一个坏主意。

如果您想提供复制语义,请提供 Clone() 方法。

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.

怼怹恏 2024-08-22 02:25:50

为什么不在对象中创建 .CopyProperties(ByVal yourObject As YourObject) 方法?

您使用内置对象吗?

Why not make a .CopyProperties(ByVal yourObject As YourObject) method in the object?

Are you using a built-in object?

二手情话 2024-08-22 02:25:50

我们可以重载 = 运算符,但不能直接重载。

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;
    }
}

这里,当您调用该运算符重载方法时,它正在调用 = 运算符本身将其转换为 int。你不能直接重载“=”,但这种代码方式的意思是一样的。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文