Reputation: 492
Here's how I want to use them:
class SecuredModel
{
public SecuredModel() { }
[Permission(Permissions.Read)]
public void restrictedMethod()
{
if (IsPermitted)
{
// code
}
}
}
I have defined here the "Permission" class:
[System.AttributeUsage(System.AttributeTargets.Method, AllowMultiple = true)]
class Permission : System.Attribute
{
private Permissions PermissionsRequired { get; set; }
public bool IsPermitted
{
// some code to check for permissions
}
public Permission(Permissions permissionsRequired)
{
this.PermissionsRequired = permissionsRequired;
}
}
The problem I am having is that I don't know how to use the attributes I've assigned to my methods. I'd like to access them from within the method, is that a possibility? If not, could I instead access them from outside the method? I haven't been able to find this usage of any of the MSDN pages I've looked at, and I've seen some answers on SO, but I feel like a lambda expression is overcomplicating this. It shouldn't be that difficult, right?
Upvotes: 0
Views: 1274
Reputation: 12857
Attributes are a way to decorate classes but they are only useful when you have some abstraction (like an IDE or some upfront processing mechanism that inspects the class) that is enforcing their purpose. They don't make sense to be used within the method/property they decorate (performance etc..)
Consider adding some extra properties (private/protected) that are set after inspecting the class, that way you are not reflecting all the time.
Here is a helpful link on attributes: Reflection - get attribute name and value on property
Upvotes: 1