C# Getter和Setter不工作

C# Getter和Setter不工作,c#,.net,C#,.net,我现在有下面的类,其中包含getter和setter public class CustAccount { public string Account { get; set; } private string account; public string AccountType { get; set; } private string accountType; public CustSTIOrder(Account ord) {

我现在有下面的类,其中包含getter和setter

public class CustAccount
{
    public string Account { get; set; }        private string account;
    public string AccountType { get; set; }    private string accountType;

    public CustSTIOrder(Account ord)
    {
        account = ord.Account;
        accountType = ord.AccountType;
    }
}

现在我意识到,使用
公共字符串帐户{get;set;}
我不需要声明
私有字符串帐户
。无论如何,现在我的私有变量
account
包含该值,但当我使用
account
获取该值时,我得到一个空值。关于我为什么得到空值有什么建议吗?

您必须将属性
帐户
与字段
帐户
连接起来:

private string account;
public string Account
{
   get {return this.account;}
   set {this.account = value;}
}

私有字段需要在属性中使用,否则您将得到一个具有不同备份存储的

public class CustAccount
{
    private string account;
    public string Account { get {return account;} set{account = value;} }        
    private string accountType;
    public string AccountType { get{return accountType;} set{accountType = value;} }  

    public CustSTIOrder(Account ord)
    {
        account = ord.Account;
        accountType = ord.AccountType;
    }
}

由于您使用的是自动属性,因此对该属性的所有引用都应该使用
Account

如果您希望使用支持字段,那么您需要在
get
集合中设置支持字段(
account

例如:

public string Account 
{ 
    get { return account; }
    set { account = value; }
}        
private string account;
“自动”特性的使用示例:

public CustSTIOrder(Account ord)
{
    Account = ord.Account;
    // the rest
}

只是不要使用
帐户
,直接使用该属性:

public class CustAccount
{
    public string Account { get; set; }        
    public string AccountType { get; set; }

    public CustSTIOrder(Account ord)
    {
        Account = ord.Account;
        AccountType = ord.AccountType;
    }
}

这些自动属性在内部有一个字段作为后盾,因此您不必编写那些琐碎的代码。

OT:有趣的是,您在类定义的末尾注释了
//end method
Account
属性和
Account
变量是不相关的。是的,因为您没有在任何地方分配Account。没有聪明的机制可以将变量
account
映射到方法
account
本身。如果确实要使用这些名称,请完整编写
get
set
例程。它不会自动为您生成私有变量。如果您使用缩写{get;set;}创建属性,那么只需使用该属性名称,在您的案例中,使用大写字母a的Account和AccountType即可s@LastCoder:正确,但更精确一点:使用自动属性确实会创建一个私有字段!但是,该私有字段将是匿名的,即对程序员隐藏,因此无法直接引用它。因此,需要通过物业进行所有访问;或者显式实现该属性,这使您可以选择将哪个字段用作该属性的支持字段。如果没有特殊需要,使用auto属性将更简单。你也可以用它来添加一个例子。对,在我的答案的第一行,它说他应该只使用
Account
。@Jeffery Khan所以如果我决定使用
public string Account{get;set;}
如何像设置私有变量
private string Account=“0000”那样设置初始化值
?通过在构造函数中设置帐户值。或者使用第一个示例(不使用自动属性),这是一个特殊的实现,在这种情况下,您需要使用一个备份字段。将backing字段设置为您希望的默认值。默认情况下,也可以使用构造函数为auto属性赋值。