簡體   English   中英

C# 為結構錯誤的屬性賦值

[英]C# assigning value to property of struct error

我有以下代碼(簡化)、一個結構和一個類。

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;

我得到錯誤

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

任何想法如何糾正?

在“明確賦值”中,一個struct要求所有字段都被賦值,然后才能調用方法,而屬性(甚至屬性設置器)就是方法。 懶惰的修復很簡單:

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

它通過明確地將所有內容設置為零來愚弄明確的分配。 然而。 IMO 真正的解決辦法是“沒有可變結構”。 可變結構會傷害你 我會建議:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM