如果您IDisposable
在具体类上实现并且接口用户知道它可能是一次性的;你可以做
IFoo foo = Factory.Create("type");
using(foo as IDisposable){
foo.bar();
}
如果foo
不执行IDisposable
,using
将达的using(null)
行之有效。
以下示例程序的输出将是
Fizz.Bar
Fizz.Dispose
Buzz.Bar
示例程序
using System;
internal interface IFoo
{
void Bar();
}
internal class Fizz : IFoo, IDisposable
{
public void Dispose()
{
Console.WriteLine("Fizz.Dispose");
}
public void Bar()
{
Console.WriteLine("Fizz.Bar");
}
}
internal class Buzz : IFoo
{
public void Bar()
{
Console.WriteLine("Buzz.Bar");
}
}
internal static class Factory
{
public static IFoo Create(string type)
{
switch (type)
{
case "fizz":
return new Fizz();
case "buzz":
return new Buzz();
}
return null;
}
}
public class Program
{
public static void Main(string[] args)
{
IFoo fizz = Factory.Create("fizz");
IFoo buzz = Factory.Create("buzz");
using (fizz as IDisposable)
{
fizz.Bar();
}
using (buzz as IDisposable)
{
buzz.Bar();
}
Console.ReadLine();
}
}