简体   繁体   English

C#中的私有/公共变量

[英]Private/Public Variables in C#

I come from Java and i have learned to never set a Variable public. 我来自Java,而且我学会了从不设置Variable公共变量。 Always make a variable private and make her accessable over setter and getter methods. 始终将变量设为私有,并使其可以通过setter和getter方法进行访问。

I started with C# the last days and im actually getting problems with this: 我在最后几天开始使用C#,而我实际上在遇到问题:

String Name { get; set; }

From other classes i can not access to the variable "Name" 从其他类中,我无法访问变量“名称”

so i thought this might be a good solution: 所以我认为这可能是一个很好的解决方案:

 String Name { public get; public set; }

but yes ... does not work. 但是是的...不起作用。

Do i have to make every variable public? 我是否必须公开每个变量?

You are defining a property, not a field. 您正在定义的是属性,而不是字段。 This is equivalent to creating a getName and setName in Java and an associated private field. 这等效于在Java中创建一个getNamesetName以及一个关联的私有字段。

The syntax you are using is shorthand for doing this. 您使用的语法是执行此操作的简写。

To make it accessible set the property to public. 要使其可访问,请将属性设置为public。

public String Name { get; set; }

If you don't want the set method to be accesible you can mark it private: 如果您不希望使用set方法,则可以将其标记为私有:

public String Name { get; private set; }

This will cause the compiler to create code equivalent to the following: 这将导致编译器创建与以下代码等效的代码:

private String _name;

public String GetName()
{
    return _name;
}

private void SetName(String name)
{
    _name = name;
}

You need to make property public 您需要public财产

public String Name { get; set; }

Class members are private by default. 默认情况下,班级成员是private的。

These are properties, not fields. 这些是属性,而不是字段。 Properties in C# are the same as getter and setter methods in Java. C#中的属性与Java中的getter和setter方法相同。 To make them public you should have public string Name { get; set;} 要使它们公开,您应该使用public string Name { get; set;} public string Name { get; set;} . public string Name { get; set;}

Generally you shouldn't have too many of these on your classes as it breaks encapsulation and is symptomatic of a bad design. 通常,您的类上不应包含太多此类内容,因为它破坏了封装并且表现出不良的设计。

@Selman22 already gave you a concise and accurate answer, extended with comments by @Mike Christensen. @ Selman22已经给您一个简洁准确的答案,并附以@Mike Christensen的评论。 (essentially, you are talking about Properties ). (本质上,您是在谈论Properties )。 You may also consider an option available in C# to use Internal access modifier, applied to types or members that are accessible only within files in the same assembly, so less visible from the outside world. 您还可以考虑使用C#中的一个选项来使用“ Internal访问”修饰符,该修饰符应用于仅在同一程序集中的文件内可访问的类型或成员,因此在外界看不见。 Best regards, 最好的祝福,

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

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