C# 在类中实现接口时,如何创建自动实现的属性?
当我第一次在类中实现接口时,我希望resharper 6或visual studio 2010将我的属性实现为自动实现的属性,而不是将其放入默认值throw new NonImplementedException();。我该怎么做?例如:C# 在类中实现接口时,如何创建自动实现的属性?,c#,class,properties,interface,C#,Class,Properties,Interface,当我第一次在类中实现接口时,我希望resharper 6或visual studio 2010将我的属性实现为自动实现的属性,而不是将其放入默认值throw new NonImplementedException();。我该怎么做?例如: public interface IEmployee { // want this to stay just like this when implemented into class ID { get; set; } } public class Emp
public interface IEmployee
{
// want this to stay just like this when implemented into class
ID { get; set; }
}
public class Employee : IEmployee
{
// I do not want the throw new NonImplemented exception
// I want it to just appear as an auto implemented property
// as I defined it in the interface
public int ID
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
}
因为这种情况一直都在发生,我发现自己必须不断地重构并手动删除那些抛出新的unlimpented()异常并手动使属性自动实现。。。痛!毕竟,我在接口中将它定义为一个自动实现的属性
非常感谢任何帮助或建议!谢谢
毕竟,我在接口中将它定义为一个自动实现的属性
不,你没有。您将其声明为不带实现的属性。这就是在接口中所能做的:您只是说实现接口的类必须提供此类属性的具体实现
就我个人而言,我会担心接口中有太多的可写属性——如果你发现这种情况“一直都在发生”,我想知道你是否在使用可能更适合抽象类的接口
关于您的确切问题:我不知道是否可以更改VS或R#为接口提供的默认实现,但老实说,我拒绝进行这些更改
编辑:在R#options“代码生成”下,您可以在引发异常、返回默认值或给出不可编译代码之间进行选择。这可能会满足你的要求。试一试,但我仍然强烈敦促您在走这条路之前仔细考虑。接口不是用来指定如何实现方法的,因此使用接口是没有办法的。一种解决方案是使用自动实现的属性创建一个抽象基类并继承该类,而不是直接实现接口。除了Jon的答案之外。。。如果您真的想更改Visual Studio的这种(开箱即用)行为,并在实现接口时创建自动属性,您可以尝试以下方法之一
NotImplementedException
,除非您更改它
但是,如果忽略建议的操作过程,而是使用Alt+Insert打开“生成”菜单,则可以选择“缺少成员”:
这将打开“生成”窗口,您可以在其中选择将属性实现为自动实现:
这将完全满足您的要求:
class Employee : IEmployee
{
public int Id { get; set; }
}
它与这个问题并不完全相关,但是,当您在一个接口中有多个这样的属性时,您可以使用另一种方法,而不是接口,您可以拥有一个类,并在主类中将该类作为返回类型引用。您可以创建一个类并在主类中引用该类。范例
public class Asset
{
public int AssetTrackingID { get; set; }
public Category AssetCategoryInfo { get; set; }
public Manufacturer AssetManufacturerInfo { get; set; }
public ManufacturerModel AssetModelInfo { get; set; }
public Status AssetStatusInfo { get; set; }
public EmployeeDetails AssetEmployeeInfo { get; set; }
public string AssetNumber { get; set; }
public string SerialNumber { get; set; }
public DateTime? AcquiredDate { get; set; }
}以下是我在VS2015中找到的快速解决方法。将类标记为抽象类,然后抽象地实现接口。这会为您添加自动属性,然后您只需将文件中的“摘要”替换为“”。然后您可以从类中删除抽象关键字。对于VS2015,我使用查找并替换宏作为解决方法:
Find:
(\r|\n| |\t)+\{(\r|\n| |\t)+get(\r|\n| |\t)+\{(\r|\n| |\t)+throw(\r|\n| |\t)+new(\r|\n| |\t)+NotImplementedException\(\);(\r|\n| |\t)+\}(\r|\n| |\t)+set(\r|\n| |\t)+\{(\r|\n| |\t)+throw(\r|\n| |\t)+new(\r|\n| |\t)+NotImplementedException\(\);(\r|\n| |\t)+\}(\r|\n| |\t)+\}
replace:
{get;set;}
完美的可能复制品!谢谢,这正是我要找的。我使用tdd编程,并且不断重构/移动/添加/删除接口中的项,因此在我的类中实现的大量接口中手动调整throw new NonImplemented()异常总是非常耗时。我使用的是resharper 6和resharper 2.x键盘布局,因此您的指令运行良好。再次感谢您的回复(也感谢所有人)!仅供参考,“default value”选项将生成一个扩展属性,该属性返回类型的默认值,并具有一个空的setter。