简体   繁体   English

类变量C#

[英]Class variable C#

Suppose I have 3 classes namely: Class1, Class2 and class3. 假设我有3个类,即:Class1,Class2和class3。 Class3 has a variable var3 . Class3有一个变量var3

Is it possible that var3 (from Class3) can only be accessed by Class1 and not by Class2 or any other classes? var3 (来自Class3)是否可能只能由Class1访问,而不能由Class2或任何其他类访问?

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. Class1Class3放在同一个程序集中,并使Class3内部。 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 如果你为class3保护var3并使class1从class3继承,那么它将起作用

Edited, when its a property 编辑,当它的财产

Eg: 例如:

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


public class Class2
{
}


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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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