How to initialize a struct in C#(如何在 C# 中初始化结构)
问题描述
我有一些代码可以在 C# 中初始化一个结构:
I have some code to initialize a struct in C#:
namespace Practice
{
public struct Point
{
public int _x;
public int _y;
public int X
{
get { return _x; }
set { _x = value; }
}
public int Y
{
get { return _y; }
set { _y = value; }
}
public Point(int x, int y)
{
_x = x;
_y = y;
}
}
class Practice
{
public static void Main()
{
Point p1;
p1.X = 1;
p1.Y = 2;
}
}
}
上面的代码给出了编译错误:
The above code gives a compiler error:
错误 CS0165:使用未分配的本地变量'p1'
error CS0165: Use of unassigned local variable 'p1'
为什么会抛出这个错误?
Why is this error being thrown?
推荐答案
你不能在结构中使用 property,直到它知道所有 fields 都已被填充在.
You can't use a property in a struct until it knows all the fields have been filled in.
例如,在您的情况下,这应该编译:
For example, in your case this should compile:
Point p1;
p1._x = 1;
p1._y = 2;
int x = p1.X; // This is okay, now the fields have been assigned
请注意您如何不必在此处显式调用构造函数...尽管在封装良好的结构中您几乎总是将必须这样做.您可以摆脱这种情况的唯一原因是因为您的字段是公开的.艾克.
Note how you don't have to explicitly call a constructor here... although in well-encapsulated structs you almost always would have to. The only reason you can get away with this is because your fields are public. Ick.
但是,我强烈建议您不要无论如何都使用可变结构.如果你真的想要一个结构,让它不可变并将值传递给构造函数:
However, I would strongly advise you not to use a mutable struct anyway. If you really want a struct, make it immutable and pass the values into the constructor:
public struct Point
{
private readonly int x;
public int X { get { return x; } }
private readonly int y;
public int Y { get { return y; } }
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
}
...
Point p1 = new Point(1, 2);
这篇关于如何在 C# 中初始化结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 C# 中初始化结构


- C# 中多线程网络服务器的模式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01