简体   繁体   中英

Class variable C#

Suppose I have 3 classes namely: Class1, Class2 and class3. Class3 has a variable var3 .

Is it possible that var3 (from Class3) can only be accessed by Class1 and not by Class2 or any other classes?

Another option in addition to the ones mentioned:

public class Class3
{
    private int var3;

    public class Class1
    {
        public void ShowVar3(Class3 instance)
        {
            Console.WriteLine(instance.var3);
        }
    }
}

Which option is the right one will depend on your context. I'd argue that whatever you do, you almost certainly shouldn't be trying to access another class's variables directly - but all of this applies to members as well, which is more appropriate.

Put Class1 and Class3 in the same assembly, and make Class3 internal. Then it will only be visible to the other classes inside the same assembly.

If you make var3 protected for class3 and make class1 inherit from class3 it'll work

Edited, when its a property

Eg:

public class Class3
{
     protected int Var3 {get;set;}
}


public class Class2
{
}


public class Class1 : Class3
{
   //access Var3 here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM