Поделиться через


Inheritance Demands

Inheritance demands applied to classes have a different meaning than inheritance demands applied to methods. You can place inheritance demands at the class level to ensure that only code with the specified permission can inherit from your class. Inheritance demands placed on methods require that code have the specified permission to override the method.

Class Inheritance Demands

An inherited demand applied to a class has the effect of demanding that all classes derived from the parent class have the specified permission. For example, if class B is to inherit from class A and class A is protected by an inheritance demand, then B must be granted that permission in order to run. If class B is granted that permission and derives from class A, then class C must also have the permission demanded by A, if it is to derive from B. This demand can be applied only declaratively.

The following example uses an inheritance demand to require that any class that inherits from this class must have the custom permission CustomPermissionAttribute. This permission is a hypothetical custom permission and does not exist in the .NET Framework. This demand is made by passing the CustomPermissionAttribute a SecurityAction.InheritanceDemand enumeration.

<CustomPermissionAttribute(SecurityAction.InheritanceDemand)> Public Class MyClass1
   Public Sub New()
   End Sub 
   
   Public Overridable Function ReadData() As String
      'Access a custom resource.
   End Function
End Class    
[C#][CustomPermissionAttribute(SecurityAction.InheritanceDemand)]
public class MyClass
{
   public MyClass()
   {    
   }   

   public virtual string ReadData()
   {
      //Access a custom resource.
   }
}

Method Inheritance Demands

If you place an inheritance demand at the method level, the specified permission will be applied to all overridden methods in a derived class. By using this declaration on specific methods, it is possible to selectively control the ability of derived classes to override the methods.

The following example specifies that all classes that derive from MyClass must have the CustomPermission permission to override the ReadData method. In this case, the attribute and SecurityAction.InheritanceDemand are applied at the method level instead of at the class level

Public Class MyClass
   Public Sub New()
   End Sub
   
   <CustomPermissionAttribute(SecurityAction.InheritanceDemand)> Public Overridable Function 
   ReadData() As String
      'Access a custom resource.
   End Function
End Class
[C#]public class MyClass
{
   public MyClass()
   {    
   }   
   [CustomPermissionAttribute(SecurityAction.InheritanceDemand)]
   public virtual string ReadData()
   {
      //Access a custom resource.
   }  
}

See Also

Extending Metadata Using Attributes | Security Demands | Creating Your Own Code Access Permissions | Adding Declarative Security Support | Code Access Security