我有一个单一的上下文对象,我希望能够从许多不同的类中访问它。我的代码看起来像这样:
Context ctx = new Context();
Section section = new Section(ctx) {
Data1 = new SomeData(ctx) { Value = 123 },
Data2 = new SomeOtherData(ctx) { Foo = "bar" },
SubSection = new Section(ctx) {
MoreData = new MoreData(ctx) { Text = "Hello!" }
}
};
但我真正想要的是看起来像这样的代码:
using(Context.New()) {
Section section = new Section() {
Data1 = new SomeData { Value = 123 },
Data2 = new SomeOtherData { Foo = "bar" },
SubSection = new Section {
MoreData = new MoreData { Text = "Hello!" }
}
};
// do something with section
}
这可行吗?我将在ASP.NET以及.exe文件中使用它(可能还会有其他东西),所以无法仅将静态或线程本地引用存储在某个位置。它不需要与上述完全相同,只需一种方式即可,这样我就不必将上下文传递给我创建的每个对象。我考虑过使用类似于“context.createSomeData()”的扩展方法,但是每个类都需要更多的样板文件,并且与您仍然需要上下文对象相比,并没有任何改进。理想情况下,应该在VS2008/.NET3.5下运行,尽管如果有任何方法可以做到这一点,我仍然会感兴趣。更新:最终通过重新设计我的方法解决了此问题,具体如下:
Section section = new Section {
Data1 = new SomeData { Value = 123 },
Data2 = new SomeOtherData { Foo = "bar" },
SubSection = new Section {
MoreData = new MoreData { Text = "Hello!" }
}
};
section.DoStuffWithContext(new Context());
虽然这可能并不适用于每个人,但它能满足我在此处的需求。如果有人提出了解决最初问题的好方法,我会让这个问题保持开放状态。
new Section(ctx) { Data1 = new SomeData { ... }, Data2 = new SomeOtherData { ... }, ... }
这样写可以吗?如果可以的话,你可以修改Section
类的属性设置器,将上下文传递给分配的值。 - user743382