简体   繁体   English

如何在C#中实现赋值运算符或什么是替代方法?

[英]How to implement assignment operator in c# or what is alternative approach?

I am looking to find a good way to skip copy constructor approach in C# and looking for a way to do same thing with assignment in code below: 我正在寻找一种很好的方法来跳过C#中的复制构造函数方法,并在下面的代码中寻找一种使用赋值执行相同操作的方法:

class Person
{
    string Name;
    int Age;
    public Person() { }
    //public Person(Person p)//copy contructor
    //{
    //    this.Name = p.Name;
    //    this.Age = p.Age;
    //}
    public Person(string name ,int age)
    {
        this.Name = name;
        this.Age = age;
    }
    public void Set(string name,int age)
    {
        this.Name = name;
        this.Age = age;
    }
    public void Get()
    {
        Console.WriteLine("{0}  {1}",Name,Age);
    }
};

        Person person= new Person("Arif",40);
        person.Get();
        //Person person2 = new Person(person);//skip copy
        Person person2 = new Person();
        person2 = person;//use assignment
        person2.Get();
        person.Set("Mahmood",44);
        person.Get();
        person2.Get();

Output I see in case of copy when copy constructor is implemented is desired one given below 下面是我希望实现复制构造函数时在复制情况下看到的输出

Arif  40
Arif  40
Mahmood  44
Arif  40

But output which I see for assignment is wrong one given below 但是我看到分配的输出是错误的以下给出的

Arif  40
Arif  40
Mahmood  44
Mahmood  44

How to get right output? 如何获得正确的输出?

If we go solely by the example you provided, you need Person to be a 'structure'. 如果仅以您提供的示例为例,则需要Person为“结构”。 They are assigned by copying a value rather than refference. 通过复制值而不是引用来分配它们。

You cannot override the operator "=" in C# See here in MSDN 您不能在C#中覆盖运算符“ =”, 请参见MSDN。

=, ., ?:, ??, ->, =>, f(x), as, checked, unchecked, default, delegate, is, new, sizeof, typeof =======> These operators cannot be overloaded =,。,?:,??,->,=>,f(x),as,checked,unchecked,default,delegate,is,new,sizeof,typeof =======>这些运算符不能是超载

Moreover, assignments that deny the normal behaviour are confusing 而且,拒绝正常行为的作业令人困惑

person1 = person2; //Your Person class
county1 = country2; // Some other class

Both are instances of classes (Person & Country) and therefore referenced. 两者都是类的实例(人员和国家),因此被引用。 Why does Person behave other than Country?!? 为什么人的行为会不同于国家/地区?!?

The copy constructor is the option to go here if you are using classes. 如果使用的是类,则可以使用复制构造函数进行复制。 A way to use the assignment operator is to use non-referenced types like primitives or a struct. 使用赋值运算符的一种方法是使用非引用类型,例如基元或结构。 However, a struct should not have functions! 但是,结构不应该具有功能! That's what classes are for. 那就是上课的目的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM