为接口赋值 属性

Assigning value to interface property

我定义了这样一个接口:

public interface myInterface {
  int SomeProperty {get;set;}
}

在继承class中,我是这样做的:

public class MyClass:myInterface {
  public int SomeProperty = 5;
}

但是我得到这个错误:

MyClass does not implement interface member myInterface.SomeProperty. 

知道我做错了什么吗?

您将 SomeProperty 声明为 field, not a property。你应该这样做:

public class MyClass:myInterface
{
  public MyClass()
  {
     SomeProperty = 5;
  }

  public int SomeProperty { get; set; }
}

或者,如果您使用的是 C# 6,则可以将其缩短为:

public class MyClass:myInterface
{
  public int SomeProperty { get; set; } = 5;
}