用户kokos通过使用关键字回答了c#的隐藏特性问题。你能详细说明一下吗?使用的用途是什么?
当前回答
Rhino模拟记录回放语法有趣地使用了using。
其他回答
它也可以用于创建作用域,例如:
class LoggerScope:IDisposable {
static ThreadLocal<LoggerScope> threadScope =
new ThreadLocal<LoggerScope>();
private LoggerScope previous;
public static LoggerScope Current=> threadScope.Value;
public bool WithTime{get;}
public LoggerScope(bool withTime){
previous = threadScope.Value;
threadScope.Value = this;
WithTime=withTime;
}
public void Dispose(){
threadScope.Value = previous;
}
}
class Program {
public static void Main(params string[] args){
new Program().Run();
}
public void Run(){
log("something happend!");
using(new LoggerScope(false)){
log("the quick brown fox jumps over the lazy dog!");
using(new LoggerScope(true)){
log("nested scope!");
}
}
}
void log(string message){
if(LoggerScope.Current!=null){
Console.WriteLine(message);
if(LoggerScope.Current.WithTime){
Console.WriteLine(DateTime.Now);
}
}
}
}
只是添加了一点我很惊讶没有出现的东西。using最有趣的特性(在我看来)是无论你如何退出using块,它总是会释放对象。这包括返回和异常。
using (var db = new DbContext())
{
if(db.State == State.Closed)
throw new Exception("Database connection is closed.");
return db.Something.ToList();
}
这与是否抛出异常或是否返回列表无关。DbContext对象总是会被释放。
“using”还可以用于解决名称空间冲突。
关于这个主题,我写了一个简短的教程,请参阅http://www.davidarno.org/c-howtos/aliases-overcoming-name-conflicts/。
using可以用来调用IDisposable。它还可以用于别名类型。
using (SqlConnection cnn = new SqlConnection()) { /* Code */}
using f1 = System.Windows.Forms.Form;
可以通过以下示例使用别名命名空间:
using LegacyEntities = CompanyFoo.CoreLib.x86.VBComponents.CompanyObjects;
正如你所看到的,这被称为使用别名指令,它可以用来隐藏冗长的引用,如果你想在你的代码中明显地引用什么 如。
LegacyEntities.Account
而不是
CompanyFoo.CoreLib.x86.VBComponents.CompanyObjects.Account
或者简单地
Account // It is not obvious this is a legacy entity
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- 如何使用JSON确保字符串是有效的JSON。网
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 如何检查IEnumerable是否为空或空?
- 自动化invokerrequired代码模式
- 在c#代码中设置WPF文本框的背景颜色
- 在c#中,什么是单子?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- c#线程安全快速(est)计数器
- 如何将此foreach代码转换为Parallel.ForEach?
- 如何分裂()一个分隔字符串到一个列表<字符串>
- 如何转换列表<字符串>列表<int>?
- c#对象列表,我如何得到一个属性的和