C# 赋值给 属性 of struct 错误

C# assigning value to property of struct error

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

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?
    }
}

在声明中

Book2.test_id = 0;

我收到错误

use of unassigned local variable 'Book2'

任何想法如何更正?

在"definite assignment"中,一个struct要求在调用方法之前分配所有字段,属性(甚至属性 setter)都是方法。懒惰的修复很简单:

var Book2 = default(pBook);
// the rest unchanged

它通过明确地将所有内容设置为零来愚弄明确的赋值。然而! IMO 真正的修复是 "no mutable structs"。可变结构 会伤害你 。我会建议:

var Book2 = new pBook("a", "b", 201, 0);

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; }
};