开发者

How can I get/set member variables from inside a static function?

I am trying to do something like this:

string strFirstName;
string strSurname;

pub开发者_运维技巧lic static bool MyItem(string FirstName, string Surname)
{
    strFirstName = FirstName; //won't work obviously
    strSurname = Surname;
}

private MyPrivateCode()
{
    string MyPrivateFirstName = strFirstName;
    string MyPrivateSurname = strSurname;
}

Obviously, it won't work. I need "MyItem" to be public static because I need to be able to access it from another Class. I'm coding in C#.


Static methods can only reference static members. The only way to have different data associated with different instances of your class is to use non-static members. Static members share the same data for all instances of a particular class.

The solution is to pass the other class (the one from which you need to be able to access the data stored in the first class) an instance of this class, and access the data you need through that instance.

It's difficult to be any more specific without more information about what exactly you'd like to accomplish.


MyItem is static. So you can't access an object's instance variables.

Static methods can only access other static variables.
The logic in this is that in run time there's only 1 static method, but may be 1000's of object instances, so how would you know who's variables to use ?

static string strFirstName;
static string strSurname;

public static bool MyItem(string FirstName, string Surname)
{
    strFirstName = FirstName; //won't work obviously
    strSurname = Surname;
}


Since every instance of the class would have its own strFirstName and strSurname, it would make no sense to set it from inside a static method: It would not be clear which one should be set.

You need to either write

static string strFirstName;
static string stdSurname;

or else

public bool MyItem(string FirstName, string Surname)

i.e. make the variables static (which usually makes no sense in this case) or make the method non-static (you can also call it from "another class" but you would need to give an instance)

PS: Also note, that MyItem must return a boolean value in order to compile correctly.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜