实现接口包括 throw new NotImplementedException ... 为什么?

Implement interface includes throw new NotImplementedException... why?

我正在使用 VS2017 社区,它昨天刚收到更新。今天我想实现一个接口,现在的实现是这样的:

public string City 
{ 
    get => throw new NotImplementedException(); 
    set => throw new NotImplementedException(); 
}

而不是这个(我所期望的):

public string City { get; set; }

为什么会发生这种变化?不确定这是否特定于 C#7 或 VS 或其他。我只知道接口的自动实现在过去一周左右发生了变化。

我的界面:

public interface IMyInterface
{
    string City { get; set; }
}

我个人希望这是一个错误。在这一点上,我们只能猜测团队改变行为的原因。

但是,一般来说,默认实现 'failing' 代码是有充分理由的:作为开发人员,您必须有意识地决定如何实现该段代码。如果方法的默认实现只是 return default(T) 怎么办?该代码将 'work' 直到有人注意到 'not implemented' 代码。

我会争辩说,对于属性,您现在通常可以说自动实现的属性是可行的方法。在 99% 的情况下,默认实现是正确的,这与上述方法推理相反。

看起来他们只是缩短了接口属性的默认实现。 2017之前的版本,接口属性默认是这样实现的:

    public string City
    {
        get
        {
            throw new NotImplementedException();
        }

        set
        {
            throw new NotImplementedException();
        }
    }

我一直认为这是对屏幕空间的浪费。就我个人而言,我不太喜欢这两种方法,但是用 NotImplementedExceptions 去除接口实现以强制您实际使用它们做一些事情是有意义的。

自动生成的代码是测试驱动开发 (TDD) 方法的一部分。该方法规定 - 首先使单元测试失败,然后编写代码来解决问题。它以测试和编码的循环进行。通过这些循环,一个任务就完成了。

它也适用于那些遵循敏捷方法并频繁添加和部署功能的应用程序。可以开发的东西很少,其他相关的稳定组件也可以投入生产。进行中的方法或属性标有未实现的标签。

[TestClass] 
public class UnitComp1 
{ 
    [TestMethod] 
    public void SalaryCalculationTest() 
    { 
        Payroll pr = new Payroll(); 
        Assert.IsTrue(da.IsValidGrossAmount(2000), "Invalid gross amount"); 
    } 
} 

//Cycle 1 - Test fails
public class Payroll
{
   public bool IsValidGrossAmount(int amount)
   {
     throw new NotImplementedException();
   }
}

//Cycle 2 - Test passes (done)
public class Payroll
{
   public bool IsValidGrossAmount(int amount)
   {
     return amount > 1000;
   }
}

Check out more, here

所以,我知道这是一个老问题,但看起来 Visual Studio 2017 现在允许您在两种样式之间进行选择(throw vs 普通旧 get;set;)。 (我使用的是 2017 社区的 15.7.5)。

为此,请转到工具=>选项=>文本编辑器=>C#=>高级,然后滚动到底部,您应该在该处有一个 Implement Interface or Abstract Class 部分。

在其中,您可以将 When generating properties 单选按钮设置为默认 "prefer throwing properties",或通过选择 "prefer auto properties".

设置为旧样式

您可以在“选项”设置中找到它: