C#实现结构体里嵌套一个结构体,如果需要把一个一个给结构体赋值
时间: 2024-06-20 11:03:04 浏览: 286
C#调用C++DLL传递结构体数组的终极解决方案
在C#中,可以通过在结构体内部定义另一个结构体来实现结构体的嵌套。定义一个嵌套结构体与定义普通结构体类似,只是它需要在结构体内部进行定义,如下面的代码所示:
```
struct Student
{
public string name;
public int age;
public Address address; //嵌套的结构体
}
struct Address
{
public string street;
public string city;
public string state;
}
```
要给结构体赋值,可以使用以下两种方式:
1. 使用默认构造函数初始化:
```
Student student = new Student();
student.name = "Tom";
student.age = 20;
student.address.street = "Main St.";
student.address.city = "New York";
student.address.state = "NY";
```
2. 使用对象初始化器:
```
Student student = new Student
{
name = "Tom",
age = 20,
address = new Address
{
street = "Main St.",
city = "New York",
state = "NY"
}
};
```
阅读全文