开发者

Some Logical OOP Concepts [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. 开发者_JAVA技巧 Closed 12 years ago.

I have a question.

class A
{
    static void m1()
    {
       int x=10;
    }
}

class B
{
    // if i want to access the variable x in b class how can i access it 

    A a = new A();
    // a. what should i write here to access x variable
}


In order to access x you must make it a field on A:

class A
{
    public int X;
}
class B
{
    static void Main()
    {
        A a = new A();
        a.X = 17;
    }
}

However it is generally bad practice to expose public fields from a class - it is better to wrap the field in a property to encapsulate it:

class A
{
    int _x;
    public int X
    {
        get { return _x; }
        set { _x = value; }
    }
}

If this syntax seems cumbersome you can simplify it a bit. C# has a feature called automatically implemented properties in which the compiler will generate the code above for you if you do this:

class A
{
    public int X { get; set; }
}


It should be either property or a public variable.


First, when asking a question, please spend just 30 seconds trying to get it right. Your code is nonsense.

call isn't a valid keyword in C#. Did you mean class? Or something else? Second, is it unreasonable to ask you to run the text through a spell checker? None of us are getting paid to answer your questions, we're doing it for free, in our own free time. So if you want answers, make it easy for us to understand and answer your questions. Don't be lazy at our expense, because then we'll be lazy too, and ignore your question.

Now, as I understand your question, you can't. x is a local variable declared inside the function. It's not visible anywhere else.


    class Class1
    {
        public int x;

        public void M1()
        {
            x = 10;
        }

    }

class ClassB
{

void Method()
{
    Class1 a = new Class1();
    a.M1();
    a.x = 5;
    //at this point the x will contain 5
}
}

The exmaple uses instance variables , not static.

To access static variables you must have a static method M1 then in ClassB you access the x variable usign the class name not the object name, like this:

Class1.x = 5;

Variable x1 must also be declared as static like: public static x = 10;

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜