简体   繁体   中英

Class or struct for backup data that later can be restored in some circumstances

I need a simple data structure to store 4 data types, an ImageSource, a Brush, a string and an enumeration so I am thinking of using a struct instead of a class:

public struct myData
{
    public myData(ImageSource myImg, Brush myBrush, string myText, myEnum e)
    {
        MyImage = myImg;
        MyBrush = myBrush;
        MyText  = myText;
        MyEnum  = myEnum;
    }

    public ImageSource MyImage { get; }
    public Brush       MyBrush { get; }
    public string      MyText  { get; }
    public myEnum      MyEnum  { get; }
}

This struct will only be used as a private within a class as a way of storing the last data received and restored it again in some circumstances.

I have read the MS guideline about choosing between an struct or class and they finally say:

CONSIDER defining a struct instead of a class if instances of the type are small and commonly short-lived or are commonly embedded in other objects.

AVOID defining a struct unless the type has all of the following characteristics:

  • It logically represents a single value, similar to primitive types (int, double, etc.).
  • It has an instance size under 16 bytes.
  • It is immutable.
  • It will not have to be boxed frequently.

In all other cases, you should define your types as classes.

... but I am asking this because I follow having doubt in my particular case. So what's better, struct or class here?

From my point of view, you should better use classes, and use properties in classes.

As vadim said, if you have no special needs, try to use classes.

Also as Bagus Tesa said, ImageSource does not conform to AVOID defining a struct unless the type has all of the following characteristics: It logically represents a single value, similar to primitive types (int, double, etc.).

But this question is very subjective, and ultimately it's up to you to understand.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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