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

时间:2014-08-07 14:58:38

标签: c# interface

我有以下界面:

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; }
}

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

2 个答案:

答案 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