You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

技术咨询:protected与internal的区别是什么?二者仅在项目内使用场景有差异吗?

Protected vs Internal in C#: Clear Breakdown for Your Questions

Hey Tal, these are fantastic questions—access modifiers can feel tricky at first, especially when their scopes overlap a bit. Let’s break this down step by step.

1. Core Differences Between Protected and Internal

Let’s start with the basics of each modifier, then contrast their scopes clearly:

  • protected: This modifier grants access to:

    • The class that defines the member
    • Any subclass that inherits from the defining class, regardless of which assembly (project/DLL) the subclass lives in
      Think of it as "family-only" access—any class that’s part of the inheritance tree can reach it, even if it’s in a separate project.
  • internal: This modifier grants access to:

    • All code within the same assembly (project/DLL) as the defining class
    • No code outside that assembly, even if it’s a subclass of the defining class
      Think of it as "team-only" access—everyone in the same project can use it, no inheritance required.

Quick Code Example to Illustrate

Suppose we have a base class in Project A:

public class BaseClass
{
    protected int ProtectedNumber = 42;
    internal int InternalNumber = 100;
}
  • In Project B (separate assembly): If we create DerivedClass : BaseClass, we can access ProtectedNumber (thanks to inheritance), but we can’t touch InternalNumber (it’s locked to Project A).
  • In Project A: A totally unrelated class RandomClass (no inheritance from BaseClass) can access InternalNumber, but it can’t access ProtectedNumber (no inheritance link).

2. Is Their Only Difference In-Project Usage?

Absolutely not—their core distinction is rooted in two entirely different access rules, not just project boundaries:

  • Protected’s scope is inheritance-based, not assembly-based. The key question is "is this class a subclass?"—not "is it in the same project?" A subclass in a totally separate DLL can still access protected members.
  • Internal’s scope is assembly-based, not inheritance-based. The key question is "is this code in the same project?"—not "is it a subclass?" Even a class with no relationship to the defining class can access internal members if they’re in the same assembly.

So in-project usage is just one piece of the puzzle. Protected cares about class hierarchies, internal cares about project/assembly boundaries—those are fundamentally different rules.

内容的提问来源于stack exchange,提问作者Tal Shloman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:33:55