简体   繁体   中英

Can you declare object types in struct

I'm really new to c# coming from c++ background I'm struggling to work with data structures in c++ I used to do that for example

struct product {
  int weight;
  double price;
} apple[10];

now the problem c# won't let me do the same because in c# when I declare an object type like apple I can't access the weight or the price now. is there a way to declare object type array? like above I know I can do that

product apple = new product();

but I receive an error cannot apply indexing with [] to an expression of type Program.product. is there a way to apply indexing with data structures all I want to do is something like this.

struct product {
  int x;
  double w;
} array[10];

for (int i = 0 ; i < 5 ; i++ ){

array[i].x = array[i - 1].x

}

I appreciate your help.

Members variables are private by default in C#, so you need to add public before type and name.

Also to create an array you need to use the new keyword.

public struct product 
{
  public int x;
  public double w;
}

var products = new product[10];

for (int i = 1 ; i < 5 ; i++ )
{
  products [i].x = products [i - 1].x; // beware 0-1 = -1
}

Instances of structs are value types, instead of instances of classes that are references to objects (hidden managed pointers to forget to manage them).

This may help you:

struct (C# Reference)

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