C#为结构错误的属性赋值

Nic*_*ick 4 c# structure

我有以下代码(简化)、一个结构和一个类。

public struct pBook
{
    private int testID;

    public string request;
    public string response;
    public Int32 status;
    public int test_id
    {
        get
        {
            return testID;
        }
        set
        {
            testID = value;
        }
    }
};

public class TestClass
{
    public static void Main(string[] args)
    {
        pBook Book1;
        pBook Book2;

        Book1.request = "a";
        Book2.response = "b";
        Book2.status = 201;
        Book2.test_id = 0;  //this doesn't work, why?
    }
}
Run Code Online (Sandbox Code Playgroud)

在声明中

Book2.test_id = 0;
Run Code Online (Sandbox Code Playgroud)

我收到错误

使用未分配的局部变量“Book2”

任何想法如何纠正?

Mar*_*ell 7

在“确定分配”中,astruct要求在调用方法之前分配所有字段,并且属性(甚至属性设置器)都是方法。一个懒惰的修复很简单:

var Book2 = default(pBook);
// the rest unchanged
Run Code Online (Sandbox Code Playgroud)

通过明确地将所有内容设置为零来愚弄明确的分配。然而!IMO 真正的解决方法是“没有可变结构”。可变结构会伤害你。我会建议:

var Book2 = new pBook("a", "b", 201, 0);
Run Code Online (Sandbox Code Playgroud)

with(注意:这使用了最新的 C# 语法;对于较旧的 C# 编译器,您可能需要进行一些调整):

public readonly struct Book
{
    public Book(string request, string response, int status, int testId)
    {
        Request = request;
        Response = response;
        Status = status;
        TestId = testId;
    }
    public string Request { get; }
    public string Response { get; }
    public int Status { get; }
    public int TestId { get; }
};
Run Code Online (Sandbox Code Playgroud)