C# - How to make a method only visible to classes that inherit the base class of the method
I have a base class that is marked as abstract. Is it possible to make a method in that base class only visible to other classes that are inheriting the base class?
Say I have Class1 that is my base class and is marked as abstract. Class2 Inherits Class1 and can make calls to all of it's public methods. I want Class3 to create 开发者_如何转开发an instance of Class2 but not be able to make calls to certain methods of Class1. I tried marking these methods as abstract themselves but then I get an error when Class2 tries to use them. The error is: "...Cannot declare a body because it is marked as abstract"
Why not declare the method protected
?
public abstract class Class1
{
protected abstract void Method1();
public abstract void Method2();
}
public class Class2 : Class1
{
protected override void Method1()
{
//Class3 cannot call this.
}
public override void Method2()
{
//class 3 can call this.
}
}
public class Class3
{
public void Method()
{
Class2 c2 = new Class2();
c2.Method1(); //Won't work
c2.Method2(); //will work
}
}
It sounds like you're looking for the protected
keyword. This limits the member tagged with protected
for use only for the declaring type or types which derive from that type.
abstract class Class1 {
protected void Method1() {
...
}
}
class Class2 : Class1 {
public void Method2() {
Method1(); // Legal
}
}
class Class3 {
public void Example() {
Class2 local = new Class2();
local.Method2(); // Legal
local.Method1(); // Illegal since Method1 is protected
}
}
You need to mark them in both Class1 and Class2 as protected
. This access modifier allows derived class(es) access to a member, but nothing outside the derived class(es) can see it.
Use protected
keyword.
I think you want a protected abstract
method/property/field. You'll have to use the override
keyword in Class2 to implement it, though. This gives Class2 access to the field (if you truly want it abstract), but does not give any classes that do not inherit from class1 access to those fields.
It's the override
that will get you around the Cannot declare a body...
message.
精彩评论