我有以下界面:
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; }
}
我有什么方法可以做到这一点吗?
答案 0 :(得分:6)
您无法使用不满足接口签名的方法(或属性)实现接口。考虑一下:
IReplaceable repl = new Agency();
repl.Parent = new OtherReplaceable(); // OtherReplaceable does not inherit Agency
类型检查器应该如何评估这个?它由IReplaceable
的签名有效,但不以Agency
的签名有效。
相反,请考虑使用explicit interface implementation,如下所示:
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
。
答案 1 :(得分:3)
你可以implement it explicitly。这就是他们存在的原因。
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