using(Class1 c = new Class1()){ c.Print(); },请问程序里用到using,必须要实现接口System.IDisposable吗?

woodyy 2009-03-27 04:53:13
using(Class1 c = new Class1())
{
c.Print();
}


请问程序里用到using语法,必须要实现System.IDisposable这个接口吗?
using的作用我已经大概了解了,我只是觉得很奇怪,为什么petshop4里某个类里也用到
了using语法,却没实现那个接口呀。

很奇怪呀,你们看这个petshop的某个类的代码。

namespace PetShop.BLL {
/// <summary>
/// This is a synchronous implementation of IOrderStrategy
/// By implementing IOrderStrategy interface, the developer can add a new order insert strategy without re-compiling the whole BLL
/// </summary>
public class OrderSynchronous : IOrderStrategy {

// Get an instance of the Order DAL using the DALFactory
// Making this static will cache the DAL instance after the initial load
private static readonly PetShop.IDAL.IOrder dal = PetShop.DALFactory.DataAccess.CreateOrder();

/// <summary>
/// Inserts the order and updates the inventory stock within a transaction.
/// </summary>
/// <param name="order">All information about the order</param>
public void Insert(PetShop.Model.OrderInfo order) {

using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required)) {

dal.Insert(order);

// Update the inventory to reflect the current inventory after the order submission
Inventory inventory = new Inventory();
inventory.TakeStock(order.LineItems);

// Calling Complete commits the transaction.
// Excluding this call by the end of TransactionScope's scope will rollback the transaction
ts.Complete();
}
}
}
}
...全文
165 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
woodyy 2009-03-27
  • 打赏
  • 举报
回复
哦~~~好像明白了。

原来不是那个OrderSynchronous 类要实现接口。

而是using()括号里边的这个类TransactionScope要实现那个接口。

明白了,明白了,谢谢Dobzhansky。
Dobzhansky 2009-03-27
  • 打赏
  • 举报
回复
我想, 你可能认为 TransactionScope 没有实现 IDisposable
woodyy 2009-03-27
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 Dobzhansky 的回复:]
你凭啥说下头那个没实现 IDisposable 呢
[/Quote]

抱歉,我是新手,你所谓的“下头”是不是指这个类的子类,实现了那个接口?

是不是这个意思?

可是如果该类不实现那个接口,能编译过去吗?
feifeiyiwen 2009-03-27
  • 打赏
  • 举报
回复
没看出那出错了
Dobzhansky 2009-03-27
  • 打赏
  • 举报
回复
MSDN Syntax


C#
public sealed class TransactionScope : IDisposable

Dobzhansky 2009-03-27
  • 打赏
  • 举报
回复
你凭啥说下头那个没实现 IDisposable 呢

62,268

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧