[英]How to get property value from another property?
我有以下界面:
public interface IReport
{
int ReportId {get; set;}
}
我有一个具有标识列属性的实体:
public int PaymentReportId {get; set;}
我需要PaymentReport
来实现IReport
在我的PaymentReport.cs里面,我做了:
public int PaymentReportId {get; set;}
public int ReportId {
get => PaymentReportId;
set {} //no need to ever set this;
}
否则编译器抱怨没有实现setter。
有更清洁的方法吗?
我从IReport的ReportId中删除了该集合,然后在该类中实现。
public interface IReport
{
int ReportId { get; }
}
public class PaymentReport : IReport
{
public int PaymentReportId { get; set; }
public int ReportId
{
get => PaymentReportId;
}
}
如果您尝试遵守SOLID,则称为接口隔离原则。
接口隔离原则(ISP)规定不应强迫客户端依赖它不使用的方法。
根据您的方法,显然违反了原则,因为类PaymentReport
确实具有基本上不需要的属性设置器。
考虑将IReport
拆分为IReportRead
和IReportWrite
并仅实现必要的操作。
public interface IReportRead
{
int ReportId { get; }
}
public interface IReportWrite
{
int ReportId { set; }
}
public class PaymentReport : IReportRead {//...}
这样你就有了清晰的抽象,而且你没有污染实现。
正如其他人所说,最干净的事情是改变界面或分成几个界面。 下面是将接口拆分为两个并在get
方案和get, set
方案中使用它们的示例:
interface IFooGet
{
int Id { get; }
}
interface IFooSet
{
int Id { set; }
}
public class FooGet : IFooGet
{
public int Id { get; }
}
public class FooGetSet : IFooGet, IFooSet
{
public int Id { get; set; }
}
如果那是不可能的(也许你不拥有接口的代码?)如果有人试图调用该属性,你可能会抛出异常。
class PaymentReport : IReport
{
public int PaymentReportId {get; set;}
public int ReportId {
get => PaymentReportId;
set => throw new NotSupportedException();
}
}
只是在set
有一个空体可能有时会导致错误隐藏https://en.wikipedia.org/wiki/Error_hiding如果将来某些代码试图调用setter并假设setter实际上做了一些有意义的事情
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.