假设我们有一个Foo班级:
public class Foo
{
public DateTime Timestamp { get; set; }
public double Value { get; set; }
// some other properties
public static Foo CreateFromXml(Stream str)
{
Foo f = new Foo();
// do the parsing
return f;
}
public static IEnumerable<Foo> GetAllTheFoos(DirectoryInfo dir)
{
foreach(FileInfo fi in dir.EnumerateFiles("foo*.xml", SearchOption.TopDirectoryOnly))
{
using(FileStream fs = fi.OpenRead())
yield return Foo.CreateFromXML(fs);
}
}
}
Run Code Online (Sandbox Code Playgroud)
为了获得观点,我可以说这些文件中的数据已经记录了大约2年,频率通常为每分钟几个Foo.
现在:我们有一个参数TimeSpan TrainingPeriod,例如大约15天.我想要完成的是致电:
var allTheData = GetAllTheFoos(myDirectory);
Run Code Online (Sandbox Code Playgroud)
并获得IEnumerable<Foo> TrainingSet, TestSet它,其中TrainingSet …
在基于实体框架的应用程序的业务逻辑层中,所有作用于DB的方法应该(正如我所听到的)包含在:
using(FunkyContainer fc = new FunkyContainer())
{
// do the thing
fc.SaveChanges();
}
Run Code Online (Sandbox Code Playgroud)
当然,为了我自己的方便,这些方法经常使用彼此,为了不重复自己.我在这里看到的风险如下:
public void MainMethod()
{
using(FunkyContainer fc = new FunkyContainer())
{
// perform some operations on fc
// modify a few objects downloaded from DB
int x = HelperMethod();
// act on fc again
fc.SaveChanges();
}
}
public int HelperMethod()
{
using(FunkyContainer fc2 = new FunkyContainer())
{
// act on fc2 an then:
fc2.SaveChanges();
return 42;
}
}
Run Code Online (Sandbox Code Playgroud)
当容器fc2被创建时,我看起来并不好看,但fc仍处于打开状态且尚未保存.所以这引出了我的第一个问题:
我得出一个结论,我可以写一个简单的守护风格的对象,如下所示:
public sealed …Run Code Online (Sandbox Code Playgroud)