[英]How can I implement an interface type using a explicit class
我有以下接口:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.