C# 如何扩展接口?

C# 如何扩展接口?,c#,.net,interface,C#,.net,Interface,我需要向接口添加一个新方法(MethodC),但只针对一个特定类。我不想阻塞当前接口(IMyInterface),而是想为这个类使用另一个接口。这个新接口将只包含一个新方法(MethodC)。但是使用新接口的类还需要使用IMyInterface中的方法 我不确定这是如何构建的。我从工厂方法返回类型IMyInterface。我不知道如何将第二个接口发回,或者我是否可以稍后再转换到它 IMyInterface - MethodA() - MethodB() //new interface for

我需要向接口添加一个新方法(MethodC),但只针对一个特定类。我不想阻塞当前接口(IMyInterface),而是想为这个类使用另一个接口。这个新接口将只包含一个新方法(MethodC)。但是使用新接口的类还需要使用IMyInterface中的方法

我不确定这是如何构建的。我从工厂方法返回类型IMyInterface。我不知道如何将第二个接口发回,或者我是否可以稍后再转换到它

IMyInterface
- MethodA()
- MethodB()

//new interface for single class
IMyInterfaceExtend
- MethodC()

//factory method definition
IMyInterface Factory()

IMyInterface myi = StaticClass.Factory()
myi.MethodA()
myi.MethodB()
// sometime later
// I know this doesn't work but kind of where I'm wanting to go
((IMyInterfaceExtend)myi).MethodC()

您有没有想过如何实现这一点?

您是否考虑过从旧接口“继承”下来<代码>公共接口IMyInterface扩展:IMyInterface?为什么演员阵容不起作用?假定底层类将实现该接口,在生产代码中,理想情况下,您将检查以确保返回的对象真正实现该接口。尽管我必须说,隐藏接口很少是良好设计的标志。如果只有一个类将实现新接口,为什么要使用它?任何时候使用新接口时,都可以指定类来代替。。。我能想到的唯一原因是模仿,真的。也许是IMyInterface的扩展方法?如果工厂发回BaseInterface,我该如何使用ExtendedInterface?向上施法?@4thSpace你只需将结果作为关键字施法。-
IMyInterface myi=StaticClass.Factory();var extended=mui作为IMyInterfaceExtend
public interface BaseInterface
{
    string FirstName { get; set; }
    string LastName { get; set; }

    void Method1();
}

public interface ExtendedInterface
{
    string FulllName { get; set; }

    void Method2();
}

public class ClassA : BaseInterface
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public void Method1()
    { 
    }
}

public class ClassB : BaseInterface, ExtendedInterface
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public string FullName { get; set; }

    public void Method1()
    {
    }

    public void Method2()
    {
    }
}