首页 > 解决方案 > 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; }
}

标签: c#classoopinterface

解决方案


也许你想要的是明确地实现接口......

例如

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

推荐阅读