![](/img/trans.png)
[英]The type 'Component' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.ComponentModel.Primitives'
[英]Why am I getting: The type 'IThirdParty' is defined in an assembly that is not referenced. You must add a reference to assembly 'ThirdPartyAssembly'?
假设有第三方程序集ThirdPartyAssembly.dll
公开以下内容:
namespace ThirdPartyAssembly
{
public interface IThirdParty
{
void GetInstance(ThirdPartyInfo info);
}
public class ThirdPartyInfo
{
public ThirdPartyInfo(string instanceText);
public string InstanceText { get; set; }
}
}
在解决方案的项目MyAssembly
之一中,我引用了ThirdPartyAssembly.dll
并实现了以下代码:
namespace MyAssembly
{
public abstract class AbstractMyClass1 : IThirdParty
{
void IThirdParty.GetInstance(ThirdPartyInfo info)
{
info.InstanceText = "some-text";
}
}
public abstract class AbstractMyClass1Consumer<T>
where T : AbstractMyClass1
{
}
}
在第二个解决方案项目MyAssemblyConsumer
我参考MyAssembly
(作为解决方案项目参考)并实现以下分类
namespace MyAssemblyConsumer
{
class MyClass1 : AbstractMyClass1
{
}
class MyClass1Consumer : AbstractMyClass1Consumer<MyClass1>
{
}
}
到目前为止,一切都编译得很好。 但是,当我将IMyClass2
添加到MyAssembly
项目时,该项目继承了具有以下抽象类的IThirdParty
接口
namespace MyAssembly
{
public interface IMyClass2 : IThirdParty
{
}
public abstract class AbstractMyClass2 : IMyClass2
{
void IThirdParty.GetInstance(ThirdPartyInfo info)
{
info.InstanceText = "some-text";
}
}
public abstract class AbstractMyClass2Consumer<T>
where T : IMyClass2
{
}
}
并尝试在MyAssemblyConsumer
实现以下类
namespace MyAssemblyConsumer
{
class MyClass2 : AbstractMyClass2
{
}
class MyClass2Consumer : AbstractMyClass2Consumer<MyClass2>
{
}
}
我在MyClass2Consumer
上遇到以下编译错误:
“IThirdParty”类型是在未引用的程序集中定义的。 您必须添加对程序集“ThirdPartyAssembly”的引用
问题为什么我不需要在第一种情况下引用 ThirdParty.dll,但在第二种情况下需要这个引用?
发生这种情况是因为在第一种情况下,您“隐藏”了您对ThirdPartyAssembly.dll
的引用。 是的,您的公共AbstractMyClass1
IThirdParty
实现了IThirdParty
,但它隐式地实现了它,因此调用IThirdParty.GetInstance()
方法的唯一方法是这样的:
var myClass1Instance = new MyClass1();
var info = new ThirdPartyInfo();
(myClass1Instance as IThirdParty).GetInstance(info); // this can be called
myClass1Instance.GetInstance(info); // <- this method doesn't exists
因此,在MyAssemblyConsumer
项目编译器的编译时,不需要了解有关IThirdParty
任何信息。 正如您所说,您的第一个案例编译成功,我想您没有这样的代码。
在第二个情况下,你暴露IThirdParty
的ThirdPartyAssembly.dll
通过您的公共IMyClass2
接口。 在这种情况下,编译器必须在编译时知道IThirdParty
接口(在您定义AbstractMyClass2Consumer<T>
那一行),这就是您收到此异常的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.