实例化后,实例变量将重置为默认值

时间:2016-07-20 14:35:37

标签: c# asp.net class visual-studio-2013

我创建了一个类来保存一些电子邮件数据:

public class EmailClass{
    public string sender;
    public string receiver;
    public string message;

    public EmailClass(string sender, string receiver, string message){
        this.sender = sender;
        this.receiver = receiver;
        this.message = message;
    }

    public string Sender { get; set; }
    public string Receiver { get; set; }
    public string Message{ get; set; }    
}

在我的网络应用程序中,我有一个页面:MyHome.aspx.cs(与EmailClass在同一名称空间中创建):

public partial class MyHome: System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        EmailClass obj = new EmailClass("sender", "receiver", "a message");
        Response.Write("Info: " + obj.Sender + " " + obj.Receiver + " " + obj.Message);
    }
}

加载Home.aspx时我的预期是显示:

Info: sender receiver a message

然而,它显示

Info: 

当我尝试在页面加载中访问它们时,EmailClass的实例变量似乎已重置为默认值。出于调试目的,我添加了一个MessageBox来显示构造函数中的实例变量值(调用构造函数并在实例化期间设置值)。

我的问题:那么是什么导致实例变量的值重置/不显示?

注意:当我显式设置对象的值时,它确实在页面加载期间显示。即:obj.Sender = "sender";

1 个答案:

答案 0 :(得分:5)

您正在混淆字段自动实现的属性this.senderthis.Sender不同。使用自动实现的属性时,您不需要这些字段。这些字段由编译器生成。

这将解决它:

public class EmailClass
{
    public EmailClass(string sender, string receiver, string message)
    {
        this.Sender = sender;
        this.Receiver = receiver;
        this.Message = message;
    }

    public string Sender { get; set; }
    public string Receiver { get; set; }
    public string Message{ get; set; }    
}

如果你想自己实现这些字段,你可以这样做:

public class EmailClass
{
    private string sender;
    private string receiver;
    private string message;

    public EmailClass(string sender, string receiver, string message)
    {
        this.sender = sender;
        this.receiver = receiver;
        this.message = message;
    }

    public string Sender 
    { 
        get { return this.sender; } 
        set { this.sender = value; }
    }
    public string Receiver
    { 
        get { return this.receiver; } 
        set { this.receiver = value; }
    }
    public string Message
    { 
        get { return this.message; } 
        set { this.message = value; }
    }
}

所以,它是第一种方式还是第二种方式。第二种方法仅在验证setter中的值或引发INotifyPropertyChanged事件时有用。