How do I specify a method that can be accessed only from derived classes of the same assembly?
Is there any way in C# to specify a method that can be access开发者_运维问答ed only from derived classes of the same assembly without using internal
access modifier?
Thanks.
You have to specify both internal as well as protected.
Give the scope of the class as internal and method scope as protected
Internal class Myclass
{
Protected void MyMethod()
{
//Do something
}
}
Read about C# Protected Internal
protected A protected member is accessible within its class and by derived classes.
internal Internal types or members are accessible only within files in the same assembly.
protected internal Access is limited to the current assembly or types derived from the containing class. * protected internal is the only access modifiers combination allowed for a member or a type.
So you need to use internal
key word after all:
protected internal memberName(){ ... };
I believe you can do something like:
public class OriginalClass { ... }
internal class DerivedClass: OriginalClass
{
protected void MemberName() { ... }
}
This way, only internal classes can see the DerivedClass
and only internal derived classes can see the portected members inside it.
And also, you still able to access the OriginalClass
from everywhere.
Ok! I imagine the situation where you would like to have more flexible control of what assembly class is from, and what class is derived from, than with 'internal' keyword. For example if you wish to check that the object is from th-a-at assembly and derives from one of the-e-e-ese classes.
You can do it through Assembly.GetAssembly() method of the type
http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getassembly.aspx
And here is the way to check if object is derived one from another.
Check if a class is derived from a generic class
So you can check all you need.
Then you can implement something like:
public static bool CheckTypeIsCorrect(Type t)
{
if(t.GetAssembly().FullName != AssemblyYouNeed) return false;
if(!(check anything you want in the class)) return false;
return true;
}
...
public void YourMethod(object value)
{
if(!CheckTypeIsCorrect(typeof(value)))
throw ArgumentException("Type of the object is not correct");
...
}
Make the function Access modifier
as Protected
in your Base Class. Like below
protected void YourFunctionName()
{
//This will be accessible in your derived class only.
}
A protected member is accessible from within the class in which it is declared, and from within any class derived from the class that declared this member.
A protected member of a base class is accessible in a derived class only if the access takes place through the derived class type.
Below is an example from MSDN
namespace SameAssembly
{
public class A
{
protected void abc()
{
}
}
private class B : A
{
void F()
{
A a = new A();
B b = new B();
a.abc(); // Error
b.abc(); // OK
}
}
}
精彩评论