简体   繁体   中英

Add Method - Object in another NS

Maybe I am looking at this wrong but I have been doing so for little over an hour.

  1. I first tried an Extension method, but that was not productive.
  2. Trying to extend the FormsAuthentication class to include a static method to return a concatenated value that is the same pattern sprinkled all over various root points.

Current Code (Option #2):

public partial class FormsAuthentication {
    public static string FormsUserCookieName () {
        return FormsAuthentication.FormsCookieName + '_' + HttpContext.Current.User.Identity.Name;
    }
}

The only thing I have not done, is created a Namespace file for the FormsAuthentication "extension" to be located.

Quite frankly, unsure if "psyching" the compiler into the resident namespace will perform any differently.

Any Suggestions on the best approach will be greatly appreciated.

Update

Based on discussions and review, seems the best approach was to implement a property for the Page class inherited by each page.

public class WebsitePage : Page {
    ....
    public string FormsUserCookieName { get { return FormsAuthentication.FormsCookieName + '_' + User.Identity.Name; } }
    ....
}

I suppose you want to create an extension-method .

Actually those do not really extend the class FormsAuthentication , as they reside in their own class and are completely independend of the extended class. Have a look at this example:

public static class MyExtensions
{
    public static string FormsUserCookieName (this FormsAuthentication) {
        return FormsAuthentication.FormsCookieName + '_' + HttpContext.Current.User.Identity.Name;
    }
}

This can now be used as if it were defined within FormsAuthentication , if you´d included the namespace where MyExtensions is defined. Thus you can write this now:

myInstanceOfFormsAuthentication.FormsUserCookieName();

However the method doesn´t really belong to that class, it is defined within MyExtensions -class and thus equivalent to the following:

MyExtensions.FormsUserCookieName(myInstanceOfFormsAuthentication);

Another approach is simply to have a wrapping-class around FormsAuthentication :

class FormsAuthenticationEx
{
    public static string FormsUserCookieName() { ... }
}

This is much clearer to the user of your API as it shows where your extensions are defined.

Extending the class won't work. All parts of a class must be marked partial and must be defined in the same assembly. You will never achieve the latter and as the class is defined as:

public sealed class FormsAuthentication

It is not partial and like most .NET Framework classes it is sealed.

Your only option is to create an extension method.

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