为什么界面显示"Interfaces cannot contain fields"?


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
    interface IInterface
    {
    }
    public interface Icar
    {
        int doors;
        string name;
        bool suv
    }
    class Car : Icar
    {
        public int doors;
        public string name;
        public bool suv;
    }
    class Program
    {
        static void Main(string[] args)
        {
            Car s = new Car { doors = 5, name = "my name", suv = true };
            Car t = new Car { doors = 2, name = "my name again", suv = false };
            Console.WriteLine("test");
            Console.ReadLine();
        }
    }
}

因为您尚未将字段设置为实际属性。接口不支持字段;如错误消息所述。

只需更改

  public int doors;
  public string name;
  public bool suv;

  int doors {get; set;}
  string name {get; set;}
  bool suv {get; set;}

因为这是不允许的。根据接口的 C# 参考:

接口可以是命名空间或类的成员,并且可以包含以下成员的签名:

  • 方法
  • 性能
  • 索引
  • 事件

C# 编程指南更详细地指出了接口中不能包含的内容:

接口不能包含常量、字段、运算符、实例构造函数、终结器或类型。接口成员会自动公开,并且不能包含任何访问修饰符。成员也不能是静态的。

相关内容

最新更新