如何编写一个包含一些一次性对象的If语句

时间:2015-08-24 20:24:43

标签: c# .net if-statement

我有以下C#代码

  iSomeObject.MyPoint(SomeConstants.cpU, 2,
                          myInterface.MySystem.MyCustomType == OtherConstants.cpProjected ? Constants.cpU : Constants.cpT,
                          1, ref t1, ref t2, ref t3);

当我运行我的专有分析工具时,它说myInterface.MySystem导致资源泄漏。

 class MyClass:MyInterface,IDisposable
 {}
  MyInterface myInterface = new MyClass();

我通过将实例myInstance强制转换回IDisposable并在其上调用Dipose()方法来明确处理它。

现在MySystem属性'在myInterface上调用get方法,其中(MySystem)的类型为IExampleInterface,进一步实现如下代码:

 class ExampleClass:IExampleClass,IDisposable
 {}

我不确定在myInter上调用一个Dipose()方法是否也会处理MySystem创建的资源,或者我是否需要在其上显式调用Dispose()方法。但所有这些都发生在IF声明条件下,我不知道如何处理这种情况并让我的代码处理掉所有一次性对象,换句话说我不确定这种情况下的C#语法以及如何处理在这种情况下处理dispoal概念。

任何建议都将受到赞赏。

3 个答案:

答案 0 :(得分:0)

如果MySystem是一个IDisposable对象,那么你的类应该在它的Dispose实现中处理该对象。

否则请修复静态分析工具。

答案 1 :(得分:0)

我想说你应该将处置放在知道你有MyClass的代码层。

using(var iSomeObject = new MyClass(...)) {
    // do something 
    iSomeObject.MyPoint(SomeConstants.cpU, 2,
                      myInterface.MySystem.MyCustomType == OtherConstants.cpProjected ? Constants.cpU : Constants.cpT,
                      1, ref t1, ref t2, ref t3);
}

答案 2 :(得分:0)

我不确定if语句是什么意思。如果在方法/属性/构造函数(无论如何)中使用一次性实例,并且它们没有作为类的实例成员作用,则应在使用后立即将其丢弃。

如果你的类中有成员实现IDisposable,那么你的类也应该实现IDisposable,并且一旦不再需要你的类的实例就应该调用Dispose(就像实现IDisposable的其他任何东西一样)。

在与实现IDisposable的实例交互时,也总是使用try / finally或using块。

最后,请参阅Microsoft的this write up ,了解有关使用IDisposable的完整详细信息和最佳做法。

public interface IExampleInterface { void DoSomething();}
public class ExampleClass : IExampleInterface, IDisposable {

   private bool _switch = true;

   public void DoSomething() {
       // lets use something disposable
       if(_switch) { // is this what you mean by in an if statement??
          var stream = new System.IO.MemoryStream();
          try {
              // do something with stream
          } finally {
              stream.Dispose(); // call dispose!
          }
       }
   }
   private System.IO.FileStream fs; // class level field
   public void Dispose(){
      // dispose of class fields here that implement IDisposable
      if(fs != null)
         fs.Dispose();
      fs = null;
   }
}