面试题答案
一键面试public
- 作用:表示访问不受限制,任何其他类都可以访问该成员。
- 类继承场景示例:
public class Animal
{
public string Name { get; set; }
public void MakeSound()
{
Console.WriteLine("Some sound");
}
}
public class Dog : Animal
{
public void Bark()
{
// 子类可以访问父类的public成员
Console.WriteLine($"{Name} is barking");
MakeSound();
}
}
在上述代码中,Animal
类的Name
属性和MakeSound
方法是public
的,Dog
类继承自Animal
,可以自由访问这些成员,并且Dog
类的实例在外部代码中也可以访问这些继承来的public
成员。
private
- 作用:表示只有包含该成员的类可以访问,对其他类,包括子类都是不可见的。
- 类继承场景示例:
public class Person
{
private string password;
public Person(string pwd)
{
password = pwd;
}
public bool CheckPassword(string input)
{
return password == input;
}
}
public class Employee : Person
{
public Employee(string pwd) : base(pwd) { }
// 这里不能直接访问父类的private成员password
// 以下代码会报错
// public void PrintPassword()
// {
// Console.WriteLine(password);
// }
}
在这个例子中,Person
类的password
字段是private
的,Employee
类继承自Person
,但不能直接访问password
字段。只能通过Person
类提供的CheckPassword
方法来间接操作password
。
protected
- 作用:表示只有包含该成员的类及其子类可以访问,对其他类不可见。
- 类继承场景示例:
public class Shape
{
protected int sideCount;
public Shape(int sides)
{
sideCount = sides;
}
protected void PrintSideCount()
{
Console.WriteLine($"This shape has {sideCount} sides");
}
}
public class Triangle : Shape
{
public Triangle() : base(3) { }
public void Display()
{
// 子类可以访问父类的protected成员
PrintSideCount();
}
}
在这个代码中,Shape
类的sideCount
字段和PrintSideCount
方法是protected
的,Triangle
类继承自Shape
,可以访问这些protected
成员。外部类不能直接访问Shape
类的protected
成员。
internal
- 作用:表示访问仅限于当前程序集内,在同一程序集内的任何类都可以访问,不同程序集的类不能访问。
- 类继承场景示例:
假设在一个程序集
MyLibrary
中有以下代码:
internal class BaseClass
{
internal int internalValue;
internal void InternalMethod()
{
Console.WriteLine("Internal method");
}
}
public class DerivedClass : BaseClass
{
public void UseInternalMembers()
{
internalValue = 10;
InternalMethod();
}
}
在另一个程序集AnotherApp
中引用MyLibrary
,但不能直接访问BaseClass
的internal
成员。这样可以在程序集内部共享一些不希望外部直接访问的功能和数据。
protected internal
- 作用:表示访问仅限于当前程序集内,或者从包含该成员的类派生的类型,在其他程序集中也可以访问。
- 类继承场景示例:
假设在
MyLibrary
程序集中有:
protected internal class BaseEntity
{
protected internal string identifier;
protected internal void SetIdentifier(string id)
{
identifier = id;
}
}
public class Product : BaseEntity
{
public void Initialize(string prodId)
{
SetIdentifier(prodId);
}
}
在同一程序集内,任何类都可以访问BaseEntity
的protected internal
成员。如果另一个程序集AnotherLibrary
引用了MyLibrary
,并且有一个类继承自BaseEntity
:
public class SpecialProduct : MyLibrary.BaseEntity
{
public void SpecialInitialize(string specialId)
{
SetIdentifier(specialId);
}
}
SpecialProduct
类可以访问BaseEntity
的protected internal
成员,而其他非继承自BaseEntity
的类在AnotherLibrary
中不能访问BaseEntity
的protected internal
成员。