C#中的公共/私有类

问题描述 投票:-2回答:1

enter image description here

在此段中,如照片所示,我们有公共班和私人班。这里的“局外人”一词实际上是什么意思?我很困惑。是用户吗?黑客?或其他任何东西。请深入解释

c# oop public
1个回答
0
投票

假设您有一堂课,例如为您发送短信。

public class SMSBuilder {

     private string _phoneNumber;
     internal string _message
     public void SMSBuilder(string phoneNumber, string message) 
     {
        _phoneNumber = phoneNumber;
        _message = message;
     }

     public void SendSms()
     {
       //code that sends sms
     }
}

为了简单起见,我保持了非常简单,但是假设您有一个功能齐全的项目,现在您想在其他一些项目中使用此短信发送功能,但实际上您希望将其部署到nuget或github,以便其他人可以使用你也上课了。

为此,您首先转到解决方案资源管理器,右键单击项目名称并选择属性,然后在应用程序选项卡的显示窗口中,有一个名为Output Type的组合框,它告诉编译器您要创建项目的类型项目编译时生成文件,如果选择类库,则项目将创建为.dll文件这个.dll文件,您可以在其他项目中使用它

所以提您的问题

如果是类,接口,结构,功能或属性,或者可能是公共/私有等。

这意味着:

如果是公开的:任何人都可以在原始项目或引用的项目中的任何地方访问它

如果属性是私有的,则意味着只能在其类中使用它。内部就像公开一样,仅在原始项目中公开,而不在引用的项目中公开。

var a = new SMSBuilder("xxx","xxx");  // you can use this line of code both in the original project and the referenced project because your class is **public**

a._phoneNumber; // would give you an error because it is defined as private this means it is only meant to be used inside of the SMSBuilder class;

a._message; // on the other hand will work on the original project but will give you an error in the reference project so internal means it is only meant to be used in the original project 

还有一个protected

关键字,如果您具有使用此关键字定义的属性,将其视为私有except,可以在继承的类中使用它

并且如果属性是内部受保护的,则意味着您可以在继承的类中使用它,但只能在原始项目中使用它

© www.soinside.com 2019 - 2024. All rights reserved.