如何使用显式类实现接口类型
本文关键字:实现 接口类型 何使用 | 更新日期: 2023-09-27 18:17:02
我有以下接口:
public interface IReplaceable
{
int ParentID { get; set; }
IReplaceable Parent { get; set; }
}
public interface IApproveable
{
bool IsAwaitingApproval { get; set; }
IApproveable Parent { get; set; }
}
我想在类中实现它,像这样:
public class Agency : IReplaceable, IApproveable
{
public int AgencyID { get; set; }
// other properties
private int ParentID { get; set; }
// implmentation of the IReplaceable and IApproveable property
public Agency Parent { get; set; }
}
我有什么办法可以做到吗?
你不能用不满足接口签名的方法(或属性)实现接口。想想看:
IReplaceable repl = new Agency();
repl.Parent = new OtherReplaceable(); // OtherReplaceable does not inherit Agency
类型检查器应该如何计算这个?它在IReplaceable
的签名下有效,而在Agency
的签名下无效。
相反,可以考虑使用这样的显式接口实现:
public class Agency : IReplaceable
{
public int AgencyID { get; set; }
// other properties
private int ParentID { get; set; }
public Agency Parent { get; set; }
IReplaceable IReplaceable.Parent
{
get
{
return this.Parent; // calls Agency Parent
}
set
{
this.Parent = (Agency)value; // calls Agency Parent
}
}
IApproveable IApproveable.Parent
{
get
{
return this.Parent; // calls Agency Parent
}
set
{
this.Parent = (Agency)value; // calls Agency Parent
}
}
}
现在,当你做这样的事情:
IReplaceable repl = new Agency();
repl.Parent = new OtherReplaceable();
类型检查器通过IReplaceable
的签名认为这是有效的,所以它编译得很好,但是它会在运行时抛出InvalidCastException
(当然,如果您不想要异常,您可以实现自己的逻辑)。但是,如果您这样做:
Agency repl = new Agency();
repl.Parent = new OtherReplaceable();
它不会编译,因为类型检查器会知道repl.Parent
必须是Agency
。
可以显式地实现它。这就是它们存在的原因。
public class Agency : IReplaceable, IApproveable
{
public int AgencyID { get; set; }
int IReplaceable.ParentID
{
get;
set;
}
bool IApproveable.IsAwaitingApproval
{
get;
set;
}
IApproveable IApproveable.Parent
{
get;
set;
}
IReplaceable IReplaceable.Parent
{
get;
set;
}
}
遗憾的是,你不能通过类实例访问它,你需要将它强制转换为接口才能使用它们。
Agency agency = ...;
agency.Parent = someIApproveable;//Error
agency.Parent = someIReplaceable;//Error
((IApproveable)agency).Parent = someIApproveable;//Works fine
((IReplaceable)agency).Parent = someIReplaceable;//Works fine