2011-10-11 53 views
5

我定义我的结构是这样的:有什么不对这种结构类型的定义

struct Test 
{ 
    private string assayName; 
    public string AssayName { get; set; } 

    private string oldUnitName; 
    public string OldUnitName { get; set; } 

    private string newUnitName; 
    public string NewUnitName { get; set; } 

    public Test(string name, string oldValue, string newValue) 
    { 
     assayName = name; 
     oldUnitName = oldValue; 
     newUnitName = newValue; 
    } 

} 

,但它给了我下面的错误:

"Error 13 Backing field for automatically implemented property 'EnterResults.frmApplication.Test.NewUnitName' must be fully assigned before control is returned to the caller. Consider calling the default constructor from a constructor initializer."

+2

对于初学者:编译器不会假定'assayName'是支持字段对于'AssayName' ... –

+0

您的属性不访问或变更支持字段。 – canon

+1

在附注上,您可能想要使用'class',而不是'struct'。 –

回答

6

嘛,有两个问题真的:

1.您使用自动属性,但随后也提供领域,存在之间没有布线二。

2.当你使用自动属性时,因为这是一个结构体,所以它们必须先被初始化。您可以通过调用默认构造函数来完成此操作。因此,修订版本将是:

struct Test 
{ 
    public Test(string name, string oldValue, string newValue) 
     : this() 
    { 
     AssayName = name; 
     OldUnitName = oldValue; 
     NewUnitName = newValue; 
    } 

    public string AssayName { get; private set; } 
    public string OldUnitValue { get; private set; } 
    public string NewUnitValue { get; private set; } 
} 
+0

正确。谢谢 – Bohn

6

你实际上并没有做任何事情与属性。试试这个:

struct Test 
{ 
    public string AssayName { get; set; } 
    public string OldUnitName { get; set; } 
    public string NewUnitName { get; set; } 

    public Test(string name, string oldValue, string newValue) : this() 
    { 
     AssayName = name; 
     OldUnitName = oldValue; 
     NewUnitName = newValue; 
    } 
} 

我认为这与结构初始化有关。注意到我添加的默认构造函数的调用似乎让它开心:)

“似乎让它开心” - 这是多么愚蠢。我探讨了与结构如何初始化有关的真正答案。调用默认的构造函数确保字段在使用结构之前被初始化。

3

您可以删除private字段assayName,oldUnitNamenewUnitName。然后,你指的是自动实现的属性在构造函数:

public Test(string name, string oldValue, string newValue) 
{ 
    AssayName = name; 
    OldUnitName = oldValue; 
    NewUnitName = newValue; 
} 
2

你也可以调用默认的构造函数:

public Test(string name, string oldValue, string newValue) : this() 
{ 
    assayName = name; 
    oldUnitName = oldValue; 
    newUnitName = newValue; 
} 

here

+0

请注意,我没有假设你的公共和私人变量是相关的(见编码大猩猩的答案) – KevinDTimm