简体   繁体   中英

extension method for a method C#

Is there a way to have extension method on the method? Example for this would be method that takes some user object as parameter and you need to do security check if that user can use that method at the very beginning of the method. Can the method have extension method like "check can this user use me" and return bool.

Thanks.

You can use Aspect Oriented Programming (AOP) to implement cross-cutting security checks in your code.

In .NET you have a choice of several AOP frameworks, for example:

In particular the PostSharp documentation has some nice examples on how to implement security using AOP .

You can't add extension method for a method with C#.

But you could use Aspect Oriented Programming (AOP) to do what you want, using PostSharp or Spring.NET for example.

I am not quite sure what you are looking for but this smells like declarative security to me.

Take a look at: http://msdn.microsoft.com/en-us/library/kaacwy28.aspx

I'm not sure if I understand your question well. However, what about this:

public static void EnsureUserHasAccess(this object obj)
{
    // check permissions, possibly depending on `obj`'s actual type
}

public static void DoSomething(this MyClass obj)
{
    // permissions check
    obj.EnsureUserHasAccess();

    // do something about `obj`
    …
}

public static void DoSomethingElse(this MyDifferentClass obj)
{
    // permissions check
    obj.EnsureUserHasAccess();

    // do something about `obj`
    …
}

Extension methods in C# are not extensions of methods (not sure I understand what that means), but methods that extend objects/classes.

If you want to inject the kind of checks you are describing into your code, you can look into PostSharp and AOP .

您可以使用madgnome的答案,它基于方面编程(很高兴看到有人在.net中使用过)或者您可以使用属性并在每个应该保护的方法中粘贴一些代码。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM