我有以下代码(简化),结构和类。
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'
任何想法如何纠正?
在“定值分配”中,astruct
要求在调用方法之前必须分配所有字段,而属性(甚至是属性设置器)就是方法。一个懒惰的解决方法很简单:
var Book2 = default(pBook);
// the rest unchanged
通过将所有内容显式设置为零来愚弄确定的分配。然而!IMO真正的解决方法是“没有可变结构”。可变结构会伤害您。我会建议:
var Book2 = new pBook("a", "b", 201, 0);
使用(注意:这使用最新的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; }
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句