如何使用显式类实现接口类型

Cha*_*had 2 c# interface

我有以下接口:

public interface IReplaceable
{
    int ParentID { get; set; }

    IReplaceable Parent { get; set; }
}

public interface IApproveable
{
    bool IsAwaitingApproval { get; set; }

    IApproveable Parent { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我想在类中实现它,如下所示:

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; }
}
Run Code Online (Sandbox Code Playgroud)

有什么方法可以做到这一点吗?

p.s*_*w.g 6

您无法使用不满足接口签名的方法(或属性)实现接口.考虑一下:

IReplaceable repl = new Agency();
repl.Parent = new OtherReplaceable(); // OtherReplaceable does not inherit Agency
Run Code Online (Sandbox Code Playgroud)

类型检查器应该如何评估这个?它的签名是有效的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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,当你做这样的事情时:

IReplaceable repl = new Agency();
repl.Parent = new OtherReplaceable();
Run Code Online (Sandbox Code Playgroud)

类型检查器通过签名来认为这是有效的IReplaceable,所以它编译得很好,但它会InvalidCastException在运行时抛出(当然,如果你不想要异常,你可以实现自己的逻辑).但是,如果您执行以下操作:

Agency repl = new Agency();
repl.Parent = new OtherReplaceable();
Run Code Online (Sandbox Code Playgroud)

它不会编译,因为类型检查器将知道repl.Parent必须是一个Agency.