I have:
- MyNameSpace.MyClass1
- MyNameSpace.MyClass2
i need to get value from MyClass1.myvar1 from MyClass2. Should I do that with static varia开发者_StackOverflow社区ble
What happens with variable value if it is static in a web application.
Im using MyClass1 as: var mClass=new MyNameSpace.MyClass1()
, and from that im using mClass.
thank you
No, you should not use a static variable here. Remember, static
means the variable is global for the application. In ASP.Net, you have a single application instance that is shared among everyone who visits your site. Using static variables can result in one user seeing another user's data.
If the value context is global, than it is ok to use static variable. Remember that if the value is updated, its updated for all users. If the data is different or belong to a user, than never use static, instead instantiate object of MyClass1
inside MyClass2
method .
you can use following approach.
Declare MyClass1.myvar1
as public and access from MyClass2
.
class MyClass1{
public int myvar1 = 7;
}
class MyClass2{
public void TestMethod(){
MyClass1 obj = new MyClass1();
int val = obj.myvar1;
}
}
In this case, your data is safe.
It is not OK to use a static variable within ASP.NET unless you take thread safety into account. A single request will generally run on a single thread. Different requests will probably run on different threads. (See http://blogs.msdn.com/b/tmarq/archive/2010/04/14/performing-asynchronous-work-or-tasks-in-asp-net-applications.aspx for some good threading information.)
Unless you study up on writing thread safe code, I would consider using the following objects instead to maintain static data:
- Application - for application-wide static data
- Session - if it's user specific static data
- HttpContext.Items - if it's data to be used by different objects within a single request
- HttpRuntime.Cache / HttpContext.Cache - to cache shared data that can have expirations / dependencies
All youneed is to make a new instance of your class2 and call your variable from created instance in class1 like
myclass1
{
string Variable = string.empty;
protected void YourMethod()
{
myclass2 c2 = new myclass2()
this.Variable = c2.Variable;
}
}
精彩评论