开发者

how to access private variable from one class to another? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 10 years ago.

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.

  1. Expose the private item via an accessor (requires the code)
  2. 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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜