简体   繁体   English

你能在结构中声明 object 类型吗

[英]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我对来自 c++ 背景的 c# 真的很陌生 我正在努力使用 c++ 中的数据结构,例如

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.现在问题 c# 不会让我这样做,因为在 c# 中,当我声明像苹果这样的 object 类型时,我现在无法访问重量或价格。 is there a way to declare object type array?有没有办法声明 object 类型数组? 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.但我收到一个错误,无法将带有 [] 的索引应用于 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. C#中的成员变量默认是private的,所以需要在type和name前加上public。

Also to create an array you need to use the new keyword.同样要创建一个数组,您需要使用 new 关键字。

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) 结构(C# 参考)

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

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