c# - C# 接口和类。接口需要的类中使用的变量不能是私有的,也不能是私有的,只能是公共的。为什么?
问题描述
我对 C# 中的接口有疑问。我制作了一个名为 IPerson 的界面,它需要一个名字和年龄。之后,我创建了一个继承自该接口的类,因此它需要一个名称和年龄。当我尝试在课堂上编写这些变量时,它们只能是公共的,我不明白为什么。
public interface IPerson
{
string name { get; set; }
int age { get; set; }
}
public class Person : IPerson
{
// If I try to make them private or protected, they don't work. and IPerson will be colored red. Only if they are public it's good, why ?
private string name { get; set; }
private int age { get; set; }
}
解决方案
也许你想要的是明确地实现接口......
例如
public interface IPerson
{
string Name { get; set; }
int Age { get; set; }
}
public class Person : IPerson
{
string IPerson.Name { get; set; }
int IPerson.Age { get; set; }
}
这些成员只能通过对接口的引用公开访问。
即您不能执行以下操作...
Person me = new Person();
Console.WriteLine(me.Name); // Won't compile
但您可以执行以下操作...
IPerson me2 = new Person();
Console.WriteLine(me2.Name); // Will compile
推荐阅读
- arrays - 声明 UIButtons 数组
- python - 在 Lambda Python 中调用发布请求时获得 401 Unauthorized
- angular - 从ckeditor 4导出pdf时出错
- python - 无法在 Django Rest Serializer 中填充图像
- python - 在熊猫中将列转换为日期时间(数据清理)
- c - 请帮忙!我正在尝试从带有空格的文件中获取输入,但我一直在无限循环。C 编程
- amazon-web-services - 我在亚马逊工作邮件中找不到我创建的组织
- python - 看不到 Kafka 主题中的数据
- python - 使用词典查找文本中正面和负面单词的数量,
- printing - 爱普生热敏打印机发现不是 USB 名称