如何在C#中更新示例数据

时间:2011-09-24 01:58:56

标签: c# silverlight

我有这个样本数据。现在它在一个单独的C#文件中定义,如下所示:

public class SampleData{

    public static ObservableCollection<Product> GetSampleData(){
        ObservableCollection<Product> teams = new ObservableCollection<Product>();
    }

}

我在obsevableCollection内加载GetSampleData()

它有效,我可以在我的程序中的任何地方获得Sample-Data

但是,如何重新设计此代码,以便我可以从课外动态创建样本数据?

2 个答案:

答案 0 :(得分:0)

您要实现的内容称为单例模式。它允许您存储对象的单个实例。

基本上您的问题是,每次调用GetSampleData时,您都会创建ObservableCollection<Product>的新实例,因此无法通过再次调用该方法获得相同的数据增益。我认为你的实际样本不是你的意思,因为在它发布的表单中它不会编译,因为你错过了return teams;

我猜你想要这样的东西:

public class SampleData
{ 
  private static ObservableCollection<Product> _Instance;

  public static ObservableCollection<Product> Instance
  {
    get
    {
       // Create a new collection if required.
       if (SampleData._Instance == null)
       {
          // Cache instance in static field.
          SampleData._Instance =  new ObservableCollection<Product>();
       }

       // Return new or existing collection.
       return SampleData._Instance;
    }
  }
}

基本上我们是在第一次调用时创建对象实例,所以当你再次调用Instance属性时,你会获得相同的实例。

像这样使用:

// Add the data to the ObservableCollection<Product>.
SampleData.Instance.Add(new dataObjectOrWhatEver());

// Get index 0 from the collection.
var someObject = SampleData.Instance[0];

答案 1 :(得分:0)

public class SampleData{

    static ObservableCollection<Product> teams = null;
    static public ObservableCollection<Product> Teams{
        get{
            if(teams == null)
                teams = GetSampleData();
            return teams;
        }
        set{
            teams = value;
        }
    }

    // make this one private
    private static ObservableCollection<Product> GetSampleData(){
        ObservableCollection<Product> t = new ObservableCollection<Product>();
        // fill t with your data
        return t;
    }
}
消费者

AND

public class MyCunsumerClass{

    // the method that uses the Team that provided by SampleData
    public void MyMethod(){
        this.flatteningTreeView.ItemsSource = SampleData.Teams;
    }

    public void MyFillerMethod(){
        var my_new_data = new ObservableCollection<Product>(); // or anything else you want to fill the Team with it.
        SampleData.Teams = my_new_data;
        // SampleData.Teams has new value you suplied!
    }

    public void MyChangerMethod(){
        var t = SampleData.Team;
        t.AnyProperty = my_value;
        t.OtherProperty = my_value_2;
        // SampleData.Team's properties changed!
    }

}