Confused about how the C # framework works

I have a structure

public struct card
{
    PictureBox picture;
    double value;
}

      

I want to make an array of this and add / remove images and value as I continue. I can not do it

card[] c = new card[13];
c[1].value = 4; 

      

How to assign, read and randomize these?

+3


source to share


3 answers


Do it value

public

.

public double value;

      

By default , members are class / struct level private

, making it inaccessible.

It is recommended to use public elements and use properties instead of fields, so it is better to use the following:



public double Value { get; set; }

      

You might want to consider creating struct

a class

as it is not very convenient. (See When to use struct ? , most of the time you will be working with classes in C #.) You can also use a dictionary of images and their meanings:

public Dictionary<Picture, double> Cards;

+6


source


A structure in C # is not equivalent to a C structure. In C #, a structure has copy-by-value semantics. This can be a little confusing.

Consider the following:

Card[] cards = new Card[13];
Card card = cards[1];
card.Value = 42;

      



You probably expect it to cards[1].Value

be 42, but you will be surprised to find out that it is not. This is partly the reason why mutable structures are evil .

Go with class

instead, which is closer to the C structure, since a copy of the class reference is passed instead of copying the value itself:

public class Card
{
    public PictureBox Picture { get; set; }
    public double Value { get; set; }
}

      

0


source


A structure is a collection of variables glued together with duct tape. If you need a bunch of independent variables tied together with duct tape, it's often better to use a structure that provides a bunch of variables glued together with duct tape than to create a class that tries to serve that purpose, or a structure that pretends to be an object. a class that tries to serve this purpose. If, however, you want something that behaves like an object, then you should use a class.

Given card

as shown, card[] foo = new card[10]

will do foo

identifies an array containing ten type references PictureBox

and ten double

. The declaration card bar;

will define space for other references PictureBox

and others double

that do not depend on anything else in the universe. The expression bar = foo[3];

will be equivalent bar.picture = foo[3].picture; bar.value = foo[3].value;

and will not establish a strong relationship between the fields bar

and "211".

Ribbon contour channel structures can be very useful for some purposes, such as storing point coordinates, but it's important to recognize them as they are. If you want the type to represent an object, use a class. Only if you want it to keep a bunch of independent but related variables, pipe-bound together, you should use struct

.

0


source







All Articles