没有添加到通用List <string>添加方法</string>

时间:2011-11-03 02:22:25

标签: c# asp.net

JobQuote类中的属性代码:

 public class JobQuote
{
// Properties
private List<string> _jobfilenames;
public List<string> JobFileNames
{
    get
    {
        if (_jobfilenames != null)
            return _jobfilenames;
        else
        {
            _jobfilenames = new List<string>();
            return _jobfilenames;
        }
    }

    set { _jobfilenames = value; }
}

用户控制中的属性代码

public JobQuote quote
{
    get 
    {
        if (ViewState["Quote"] != null)
            return (JobQuote)ViewState["Quote"];
        else
        {
            JobQuote newQuote = new JobQuote();
            return newQuote;
        }   
    }
    set { ViewState["Quote"] = value; }
}

在UserControl的try块中的代码,其中字符串未被添加到字符串的通用列表中:

try
        {
            string filename = System.IO.Path.GetFileName(FileUploader.FileName);
            quote.JobFileNames.Add(filename); 
        }     

我做错了什么?

2 个答案:

答案 0 :(得分:5)

您正在从视图状态读取,但您从未分配。

public JobQuote quote 
{ 
    get  
    { 
        if (ViewState["Quote"] != null) 
            return (JobQuote)ViewState["Quote"]; 
        else 
        { 
            // you only construct a new instance but you dont assign it to the viewstate
            JobQuote newQuote = new JobQuote(); 
            // add the following line to fix the problem
            // ViewState["Quote"] = newQuote;
            return newQuote; 
        }    
    } 

这意味着下次引用quote属性时,将创建一个新的JobQuote实例而不是返回旧的JobQuote实例

实现这一目标的一个简洁方法是:

public JobQuote Quote
{
    get
    {
        JobQuote result = ViewState["Quote"] as JobQuote;
        if (result == null)
        {
            result = new JobQuote();
            ViewState["Quote"] = result;
        }

        return result;
    }
}

答案 1 :(得分:2)

您每次都会返回一个新的JobQuote实例。试试这个:

public JobQuote quote
{
    get 
    {
        if (ViewState["Quote"] != null)
            return (JobQuote)ViewState["Quote"];
        else
        {
            JobQuote newQuote = new JobQuote();
            ViewState["Quote"] = newQuote;
            return newQuote;
        }   
    }
    set { ViewState["Quote"] = value; }
}

或:

public JobQuote quote
{
    get 
    {
        if (ViewState["Quote"] == null)
            ViewState["Quote"] = new JobQuote();

        return (JobQuote)ViewState["Quote"];
    }
    set { ViewState["Quote"] = value; }
}