how to access private variable from one class to another? [closed]
In class A I am have a private variable that I want to access it from another class. Is 开发者_如何学运维it possible? Give me the solution.
The private variable is supposed to be private, so there's no direct way to do this. There are a couple of things you could do.
- Expose the private item via an accessor (requires the code)
- Use reflection to poke around in the object and find it (see here)
If you want to access it from "outside" you will have to make it public. But better would be to wrap a property around it. Then you could even give readonly access.
public class MyClass
{
private int myPrivateInt;
public int PublicInt
{
get { return myPrivateInt; }
set { myPrivateInt = value; } // or remove this line for readonly access
}
}
I don't think you can access a private variable from another class.
Um...it is called private
for a reason. Make it public
?
The whole purpose of the "private" access modifier is to prevent this. I think you're looking for moving the variabele to a shared base class or using the "internal" access modifier to restrict accessibility to the classes in the same assembly.
If you really want to access it you can use reflection, but that's something you should try as a last resort. For example, if you use it to access private things in a 3th party library future versions of that lib (with the same public API) can break your application.
If you could access them, then there wouldn't not be any point in making them private.
However, in practice, get, set are usually implemented if you need access to such members.
精彩评论