简体   繁体   中英

How to get property value from another property?

I have the following interface:

public interface IReport
{
    int ReportId {get; set;}
}

I have an entity that has identity column property:

public int PaymentReportId {get; set;}

I need the PaymentReport to implement IReport

Inside my PaymentReport.cs I did:

public int PaymentReportId {get; set;}

public int ReportId {
    get => PaymentReportId; 
    set {} //no need to ever set this;
}

Otherwise the compiler was complaining about no setter implemented.

Is there a cleaner way to do this?

I removed, the set from the ReportId of IReport and then implemented in the class.

public interface IReport
{
    int  ReportId { get;  }
}

public class PaymentReport : IReport
{
    public int PaymentReportId { get; set; }
    public int ReportId
    {
        get => PaymentReportId;
    }
}

If you try to adhere to SOLID there is principle called interface segregation.

The interface-segregation principle (ISP) states that no client should be forced to depend on methods it does not use.

With your approach the principle is obviously violated as class PaymentReport does have property setter which is essentially not needed.


Consider to split the IReport to IReportRead and IReportWrite and implement only what is necessary.

public interface IReportRead
{
    int ReportId { get; }
}

public interface IReportWrite
{
    int ReportId { set; }
}

public class PaymentReport : IReportRead {//...}

That way you have clear abstraction and you are not polluting the implementation.

As others said, the cleanest thing would be to change the interface or split into several interfaces. Here is an example of splitting interface into two and use them in both the get scenario and the get, set scenario:

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; }
}

If that is not possible (maybe you don't own the code for the interface?) you might throw an exception if someone tries to call the property.

class PaymentReport : IReport
{
    public int PaymentReportId {get; set;}

    public int ReportId {
        get => PaymentReportId; 
        set => throw new NotSupportedException();
    }
}

Just having a empty body in the set may sometime lead to error hiding https://en.wikipedia.org/wiki/Error_hiding if some code in the future tries to call setter and makes the assumption that the setter actually does something meaningful

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM