I have one interface like below
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?
}
How can I expose only particular method and prevent other.
For this kind of requirement go for Abstract class not interface because in interface all methods are public by default., that is one of the difference between Abstract class and interface.
In interface you cannnot put modfier like private and public, all the methods are public by default.
You could hide the method by explicit implementation. I'd say its a bad idea and you should probably split your interface in two instead, but it is possible
public class MyClass {
public int I1.subtract(int a, int b) {
throw new NotImplementedException();
}
}
When done like this subtract will only be visible when the object
is cast as I1
the concept of interface says that you if you implement an interface you need to implement all the methods
so I think it can't be done
Further more the default methods of interface
are public
So when you are going to defining it, it should be public
only.
Here is a link for better understanding of Interfaces
http://www.codeproject.com/Articles/18743/Interfaces-in-C-For-Beginners
Here is a link which depicts the difference between Interface
and abstract class
http://www.codeproject.com/Articles/11155/Abstract-Class-versus-Interface
Not sure why you need such behavior. If you just want one of the methods to be available to the MyClass object, you can use explicit interface implementation for that particular method
public class Myclass : I1
{
public int add(int a, int b)
{
return 1;
}
public int I1.subtract(int a, int b)
{
return 2;
}
}
In this case when you create an object of MyClass, you will have only add method, not subtract. To access subtract, you will have to use the reference type of I1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.