确保只有实现某个接口的类才能调用方法? C#?

问题描述:

好吧,这可能是一个新手问题。所以道歉。 比方说我有等的方法类:确保只有实现某个接口的类才能调用方法? C#?

public class A 
{ 
    public void DoSomething(long x) 
    { 
    } 
} 

现在我要确保调用DoSomething的任何对象或类()必须实现一定的接口一样ISomethingInterface?

在C#中可以这样做吗? 感谢

+6

小心解释为什么? – 2014-09-24 14:52:37

+8

为什么不反转它并使该方法成为界面合同的一部分。该方法可能需要A类型的参数。 – 2014-09-24 14:52:40

+3

听起来像[XY问题](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)。如果你能说出你想要解决什么问题会更好? – 2014-09-24 14:55:21

的问题是那样的陌生,因为你试图实现类似的接口方案的东西,但那种上攻下。

如果你真的想只实现某个接口的类能够调用一些特定的方法我会执行它的扩展方法:

public static void DoSomething(this IFoo foo, long x) 
{ 
    .... 
} 

现在,你只能通过一个IFoo类型的对象调用DoSomething(long x)。有关更多信息,请参阅extension methods

当然的等效解决方案,但不是那么方便或优雅是简单地实现,像这样一个静态方法:

public static void DoSomething(IFoo foo, long x) { ... } 

要切换调用仅IFoo对象DoSomething路过一个IFoo对象作为参数。扩展方法本质上是该解决方案的语法糖。

但是,除非您无权访问IFoo的实施(第三方代码)或更改界面是您无法承受的重大更改,否则这种情况确实没有意义。如果你有访问权限或可以承受中断,那么只需使界面成为DoSomething的一部分。这样所有的IFoo对象将有一个DoSomething方法。

不知道我是否正确理解你的问题。

public class A : IA 
{ 
     public void DoSomething(long x) 
     { 
      } 
} 

public interface IA 
{ 
    void DoSomething(long x) 
} 


/*Some method somewhere*/ 
public void DoThisThing() 
{ 
    IA a = new A(); 

    a.DoSomething(10); 
} 

你是那种对行权,但它的作品倒过来。界面告诉你你可以做什么,它就像一个合同。

现在你可以执行你在其他类确保你只能叫DoSomething

public class B : IA 
{ 
    public void DoSomething(long x) 
    { 
     // B's custom implementation 
    } 

    public void IWantSomethingElse(string s) 
    { 
     // this is only class specific and cannot be called from the interface 
    } 
} 

/* Some method somewhere */ 
public void DoThisThing() 
{ 
    IA a = new B(); 

    a.DoSomething(2); 

    // here there is no way to call IWantSomethingElse because the its not on the interface 
} 

如果你真的要执行,其中用户必须实现界面B1,如果他们也有一个场景,然后你合同可以简单地标记一个接口来重新实现另一个接口。见MSDN - Interfaces

public interface A 
{ 
    void a(); 
} 

public interface B : A 
{ 
    void b(); 
} 

public class Foo: B 
{ 
    public void a() 
    { 
    } 


    public void b() 
    { 
    } 
} 

如果他们不执行这两种方法,那么这将抛出一个编译时错误。

你可能想使用,而不是实现一个接口的功能的抽象类:

public abstract class MyAbstractClass 
{ 
    //This one HAS to be defined in the inheritor class, like an interface 
    public abstract void DoSomeOtherThing(); 

    //This is your function that can only be called by objects that inherit from this class. 
    protected void DoSomething() 
    { 
     //use your protected method here 
    } 
} 

public class MyClass : MyAbstractClass 
{ 
    public MyClass() 
    { 
     DoSomething(); 
    } 

    public override void DoSomeOtherThing() 
    { 

    } 
} 
+0

我喜欢这种方法,我认为在这种情况下,它更接近OP要求的内容。我个人会这样做。 – 2014-09-24 15:20:00