2013-02-21 42 views
2

我有一个像下面如何防止暴露其他接口方法?

public interface I1 
{ 
public int add(int a , int b); 

public int subtract (int a, int b); 

} 

public class Myclass : I1 
{ 
//here I can access both the methods of interface I1 
//add and subtract but i want to expose only add not subtract method 
//How can I achieve this? 

} 

我怎么能只暴露特定的方法以及防止其他一个接口。

+1

你不能阻止它,但你可以用[Explicit interface implementation](http://msdn.microsoft.com/en-us/)隐藏“Myclass”类型的方法(但不能键入'I1') library/aa664591(v = vs.71).aspx):“*显式接口成员实现只能通过接口实例*访问,并且在这种情况下仅由其成员名称引用。” – 2013-02-21 07:13:19

回答

2

您可以通过显式实现隐藏该方法。我想说的是一个坏主意,你或许应该一分为二的接口,而不是,但它有可能

public class MyClass { 
    public int I1.subtract(int a, int b) { 
     throw new NotImplementedException(); 
    } 
} 

当这样做加减才可以看到当object塑像作为I1

3

对于这种类型的需求,去抽象类没有接口,因为在接口中所有的方法默认是公共的,这是抽象类和接口之间的区别之一。

在界面中,你不能像private和public一样修改,所有的方法默认都是公共的。

1

接口的概念说,你if you implement an interface you need to implement all the methods所以我认为这不能做

进一步的interface默认的方法是public
所以,当你要定义它,它应该是唯一public
这里是为更好地了解Interfaces
http://www.codeproject.com/Articles/18743/Interfaces-in-C-For-Beginners
链接下面是描述你为什么需要这样的行为Interfaceabstract class之间
http://www.codeproject.com/Articles/11155/Abstract-Class-versus-Interface

1

不知道的差别的链接。如果你只是想的方法之一是提供给MyClass的对象,你可以使用显式接口实现针对特定方法

public class Myclass : I1 
    { 
     public int add(int a, int b) 
     { 
      return 1; 
     } 

     public int I1.subtract(int a, int b) 
     { 
      return 2; 
     } 
    } 

在这种情况下,当你创建MyClass的一个对象,你会只添加方法,不减。要访问减法,必须使用参考类型I1