C#中的接口转换? [英] Interface casting in C#?
本文介绍了C#中的接口转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个界面:
I have an interface:
namespace IVR.VoiceElementsEngine
{
public interface IVoiceResource
{
void ClearDigitBuffer();
}
}
执行:
And the implementation:
namespace IVR.VoiceElementsEngine
{
public class VoiceElementsResource:IVoiceResource
{
private readonly VoiceResource _voiceResource;
public VoiceElementsResource(VoiceResource voiceResource)
{
_voiceResource = voiceResource;
}
public void ClearDigitBuffer()
{
_voiceResource.ClearDigitBuffer = true;
}
}
}
现在在另一个班级,我有
Now in another class, I have
namespace IVR.VoiceElementsEngine.CallObjects
{
public class VoiceElementsLine : ILine
{
public IVoiceResource IncomingVoiceResource { get; set; }
public VoiceElementsLine()
{
}
public VoiceElementsLine(IVoiceResource voiceElementsResource):this()
{
IncomingVoiceResource = voiceElementsResource;
}
}
}
在我与Moq的单元测试中,我有:
In my unit test with Moq, I have:
namespace IVR.Tests
{
public class VoiceElementsLineTest
{
[Fact]
public void PlayPromptTextToSpeech_Should_Play_A_Text()
{
// ARRANGE
var voiceResourceMock = new Mock<IVoiceResource>();
var voiceResource = voiceResourceMock.Object;
var line = new VoiceElementsLine(voiceResource);
我收到错误:
错误CS1503参数1:无法从'VoiceElements.Interface.IVoiceResource'转换为'IVR.VoiceElementsEngine.IVoiceResource'
我猜它是为具体实现构建接口问题。如何解决?
I got the error:
Error CS1503 Argument 1: cannot convert from 'VoiceElements.Interface.IVoiceResource' to 'IVR.VoiceElementsEngine.IVoiceResource'
I guess that it is "cast an interface to a concrete implementation" issue. How to fix it?
推荐答案
看起来你有两个版本的界面。一个在VoiceElements.Interface中,另一个在IVR.VoiceElementsEngine中。为了能够进行转换,你必须实现相同的接口实例。
当我从加载的程序集中加载单个接口时,我遇到了类似的问题直接引用它。这不起作用,因为它们不是同一个实例。
你必须拥有两个类都实现的接口版本。
It looks like you have two versions of the interface. One in VoiceElements.Interface and another in IVR.VoiceElementsEngine. To be able to cast you must implement the same instance of the interface.
I had a similar problem when I was loading a single interface from a loaded assembly as well as referencing it directly. This did not work because they were not the same instance.
You must have a version of the interface that both classes implement.
这篇关于C#中的接口转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文