What's the difference between struct and class in .NET?

前端 未结 19 1780
一向
一向 2020-11-22 01:51

What\'s the difference between struct and class in .NET?

19条回答
  •  佛祖请我去吃肉
    2020-11-22 02:03

    Just to make it complete, there is another difference when using the Equals method, which is inherited by all classes and structures.

    Lets's say we have a class and a structure:

    class A{
      public int a, b;
    }
    struct B{
      public int a, b;
    }
    

    and in the Main method, we have 4 objects.

    static void Main{
      A c1 = new A(), c2 = new A();
      c1.a = c1.b = c2.a = c2.b = 1;
      B s1 = new B(), s2 = new B();
      s1.a = s1.b = s2.a = s2.b = 1;
    }
    

    Then:

    s1.Equals(s2) // true
    s1.Equals(c1) // false
    c1.Equals(c2) // false
    c1 == c2 // false
    

    So, structures are suited for numeric-like objects, like points (save x and y coordinates). And classes are suited for others. Even if 2 people have same name, height, weight..., they are still 2 people.

提交回复
热议问题