How to use a a string of one class in another class?
I have a class in test.cs
in which I have a string value string user="testuser"
. I want to use the test.cs's us开发者_开发技巧er
value in another class. How can I do this?
Declare the string public:
public string user = "testuser";
Then you can access it from another class via
Test.user
However, depending on what exactly you want, you should perhaps make the field read-only:
public readonly string user = "testuser";
Or use a property, bound to a backing field:
public string User
{
get { return this.user; }
}
In fact, properties are the canonical way of making information accessible from the outside except for very few, very special cases. Public fields are generally not recommended.
As Ant mentioned in a comment, there is also the option of making it a constant (assuming it is, in fact, a constant value):
public const string user = "testuser";
Make a public property.
Public string TestUser
{
get { return testUser;}
}
You should make a property of user and expose this to any other class that want to read or write it's value.
class MyClass
{
private static string user;
public static string User
{
get { return user; }
set { user = value; }
}
}
class MyOtherClass
{
public string GetUserFromMyClass()
{
return MyClass.User;
}
}
public class AClass
{
// declarations
private string _user = "testUser";
// properties
public string User { get { return this._user;} set { this._user = value; } }
}
then call your class property, e.g.
AClass myClass = new AClass();
string sYak = myClass.User;
As suggested in the earlier answers, making "user" into a Property is the ideal technique of accomplishing this. However, if you want to expose it directly anyhow, you should use static to avoid having to instantiate an object of that class. In addition, if you don't want the demo class to manipulate the value of user, you should declare is readonly as well, like below
public static readonly user="text user";
精彩评论