开发者

how do i use a class without instantiating it?

I have class:

static class Get开发者_运维技巧Role
    {
        public static string OfUser(string username)
        {
            string result="None";
            foreach (string key in WebConfigurationManager.AppSettings)
            {
                if (WebConfigurationManager.AppSettings[key].Contains(username))
                {
                    result = WebConfigurationManager.AppSettings[key];
                    break;
                }
            }

            return result;
        }
    }

i would like to use it lik ethis

string role = GetRole.OfUser(username);

or like this even better:

string role = GetRole(username);

how do i do this?


i would like to use it like this

string role = GetRole.OfUser(username);

So do so; that appears to be correct. Did you try it?

or like this even better:

string role = GetRole(username);

That won't work; you have to specify the method you're calling as well as what class it comes from.

If you had a static void GetRole inside the same class as the code that you're calling it from, then you could do that.


However, just because you can do something doesn't mean you should. The natural way to do "get the role of a user" is to call a method that belongs to the user itself. That in turn implies having a User class which you instantiate for each user.


It's a little late but it can be done easily

using static MyProjectNameSpace.GetRole;

now you can use your method directly

OfUser("NewUserName");


You pretty much nailed it with your first example of how to use it:

string role = GetRole.OfUser(username);

A static member indicates that it doesn't have an instance of whatever type is declaring it. The only thing that might be giving you trouble is that your class is internal; which means you can't access it from a different assembly. Try making it public static class GetRole.


string role = GetRole.OfUser(username);

you are trying to use the variable of the method before it has been set... the method checks that AppSettings[key].Contains(username))and then returns an output so the method is expecting a string input like this...

string role = GetRole.OfUser("NewUsername");

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜