隐式转换为'System.IDisposable'错误

问题描述 投票:11回答:10

这就是我想要做的

private KinectAudioSource CreateAudioSource()
{
    var source = KinectSensor.KinectSensors[0].AudioSource;
    source.NoiseSuppression = _isNoiseSuppressionOn;
    source.AutomaticGainControlEnabled = _isAutomaticGainOn;
    return source;
}
private object lockObj = new object();
private void RecordKinectAudio()
{
    lock (lockObj)
    {
        using (var source = CreateAudioSource())
        {
        }
    }
}

'using'语句给出了一个错误,指出 - “'Microsoft.Kinect.KinectAudioSource':在using语句中使用的类型必须可以隐式转换为'System.IDisposable'”。如何消除此错误,这是什么意思?

c# kinect
10个回答
17
投票

我参加聚会很晚,但我应该说:

如果在使用using语句中的上下文时遇到此错误,则必须添加reference to Entity Framework


-1
投票

您应该将System.Data.Linq添加到项目中的References。这解决了我的问题。


14
投票

你可以这样创建:

public class HelloTest : IDisposable
{
    void IDisposable.Dispose()
    {

    }

    public void GetData()
    {

    }
}

之后你就可以创建像这样的对象了

using (HelloTest Ht = new HelloTest())
        {
            Ht.GetData();
        }

我希望上面的例子很有用


5
投票

在创建一个我忘记通过Nuget Package Manager安装ENTITY FRAMEWORK的新项目时,我遇到了类似的问题。很抱歉,如果这与kinect无关,但是当我在VS中寻找错误时谷歌就把我带走了。


4
投票

Using关键字需要IDisposable接口实现。如果你得到错误'Microsoft.Kinect.KinectAudioSource':type used in a using statement must be implicitly convertible to 'System.IDisposable.

所以它意味着像约阿希姆说KinectAudioSource不是IDisposable

你可以使用而不是using

try
{
    Execute();
}
finally
{
    CleanupPart();
}

using相当于try-finally。当你想在最后做一些清理并且不关心异常时,你将只使用try-finally


0
投票

KinectAudioSource应该实现IDisposable接口,以便与使用块一起使用。未实现Idisposable的类无法在using语句中实例化。

通常,当您使用IDisposable objAs规则时,当您使用IDisposable对象时,您应该在using语句中声明并实例化它。 using语句以正确的方式调用对象上的Dispose方法,并且(如前所示使用它时)一旦调用Dispose,它也会导致对象本身超出范围。在using块中,该对象是只读的,不能修改或重新分配,MSDN


0
投票

KinectAudioSource不是IDisposable,所以它不能用于using区块。您可能要做的是在完成录制时关闭数据流(which does implement IDisposable),例如;

private Stream CreateAudioStream()
{
    var source = KinectSensor.KinectSensors[0].AudioSource;
    source.NoiseSuppression = _isNoiseSuppressionOn;
    source.AutomaticGainControlEnabled = _isAutomaticGainOn;
    return source.Start();
}
private object lockObj = new object();
private void RecordKinectAudio()
{
    lock (lockObj)
    {
        using (var source = CreateAudioStream())
        {
        }
    }
}

0
投票

从System.EnterpriseServices版本2添加.NET引用也将解决该错误。如果您要从旧版本进行转换,并且您有多次使用“using”关键字进行替换,则此功能尤其有用


0
投票

发生System.IDisposable错误是因为您尝试打开的连接可能不会自动关闭,超出打开连接的范围。

从using()子句中排除模型连接创建,以便它保持为:

var source = new CreateAudioSource(); / *其余代码在这里* /

还要确保不会为对象创建省略'new'关键字。


0
投票

创建新的控制台应用程序时遇到了类似的问题。我忘了在项目中添加ENTITY FRAMEWORK参考。

添加有关ENTITY FRAMEWORK的参考解决问题。

© www.soinside.com 2019 - 2024. All rights reserved.