Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# protected

作者:穹上之月   发布日期:2025-08-05   浏览:62

using System;

namespace ProtectedExample
{
    // 定义一个基类
    public class BaseClass
    {
        // 使用 protected 修饰符,派生类可以访问,但外部不能访问
        protected string protectedMessage = "This is a protected message.";

        // 定义一个受保护的方法,只有派生类可以访问
        protected void ProtectedMethod()
        {
            Console.WriteLine("This is a protected method.");
        }
    }

    // 定义一个派生类
    public class DerivedClass : BaseClass
    {
        // 派生类可以访问基类的受保护成员
        public void DisplayProtectedMessage()
        {
            Console.WriteLine(protectedMessage);
        }

        public void CallProtectedMethod()
        {
            ProtectedMethod();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            DerivedClass derived = new DerivedClass();
            derived.DisplayProtectedMessage(); // 输出: This is a protected message.
            derived.CallProtectedMethod();     // 输出: This is a protected method.

            // 注意:以下代码会报错,因为 protectedMessage 和 ProtectedMethod 是受保护的,不能在类外部直接访问
            // BaseClass baseClass = new BaseClass();
            // Console.WriteLine(baseClass.protectedMessage); // 错误
            // baseClass.ProtectedMethod();                   // 错误
        }
    }
}

解释说明:

  • protected 修饰符用于声明成员(如字段、方法、属性等),使得这些成员只能在定义它们的类及其派生类中访问。
  • 在上面的示例中,BaseClass 中的 protectedMessage 字段和 ProtectedMethod 方法是受保护的,因此只能在 BaseClass 或其派生类 DerivedClass 中访问。
  • 如果尝试在类外部(如 Main 方法中)直接访问这些受保护的成员,则会导致编译错误。

上一篇:c# newtonsoft.json

下一篇:delegate c#

大家都在看

c# 二进制

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

.net和c#

c#获取系统时间

c#游戏开发

c#网络编程

c# rectangle

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站