简体   繁体   中英

C# assigning value to property of struct error

I have the following code (simplified), a structure and a 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?
    }
}

At the statement

Book2.test_id = 0;

I get the error

use of unassigned local variable 'Book2'

Any ideas how to correct?

In "definite assignment", a struct requires all fields to be assigned before methods can be called, and properties (even property setters) are methods. A lazy fix is simply:

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

which fools definite assignment by explicitly setting everything to zero. However. IMO the real fix here is "no mutable structs". Mutable structs will hurt you . I would suggest:

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

with (note: this uses recent C# syntax; for older C# compilers, you may need some tweaks):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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