如何让方法返回几乎相同的类之一?

问题描述 投票:0回答:2

我正在将一种新的支付方式整合到我们的服务项目中。我把一切都编码了。现在我希望它能够方便地遵循 Solid 原则。但是,我对如何克服案件感到困惑。 我们的服务已经有一个名为 GetPaymentProfile 的方法,并返回一个名为 PaymentProfile 的类。集成后,我必须添加一个新的 PaymentProfile 和方法,因为这个新类有一个新属性。

因此,我获得了两个类和两个方法。每个步骤都不必要地编码两次。我只是想让你告诉我如何克服这个问题。

类中预先存在的方法:

public class PaymentProfile
{
    public String Property1 = "";
    public String Property2 = "";
    public String Property3 = "";
    public String Property4 = "";
}

public PaymentProfile GetPaymentProfile(long aTicketType) {..}

集成后得到的类和方法

public class PayCorePaymentProfile
{
    public String Property1 = "";
    public String Property2 = "";
    public String Property3 = "";
    public String Property4 = "";
    public String Property5 = "";
}

public PayCorePaymentProfile GetPayCorePaymentProfile(long aTicketType) {..}

我是怎么想的

创建一个基类,然后将所有子类与该基类绑定 类,但我认为它不适合这种情况。因为我会 返回没有新属性的基类。

如果我把所有东西都放在这个基类中,旧模型就会有一个新模型 不必要的财产。

*抱歉语法规则和错误

c# design-patterns coding-style clean-architecture solid-principles
2个回答
2
投票

您需要使 PayCorePaymentProfile 成为 PaymentProfile 的子项。在这种情况下,在 GetPaymentProfile 方法中,您将能够返回 PayCorePaymentProfile。

public class PaymentProfile
{
    public string Property1 = "";
    public string Property2 = "";
    public string Property3 = "";
    public string Property4 = "";
}

public class PayCorePaymentProfile : PaymentProfile
{
    public string Property5 = "";
}

public PaymentProfile GetPaymentProfile(long aTicketType)
{
    if (usePayCore)
        return new PayCorePaymentProfile(); // You can return a child of PaymentProfile
    else
        return new PaymentProfile(); // Or just return a PaymentProfile
}

我希望这会有所帮助。


1
投票

可以有 1 个接口/基类(具有公共属性)和 2 个具有特定属性的实现。

public abstract class Profile
{
    public string Property1 {get;set;}
    public string Property2 {get;set;}
    public string Property3 {get;set;}
    public string Property4 { get; set; }
}

public class PayCorePaymentProfile : Profile
{
    public string Property5 { get; set; } = "9";
}

public class PaymentProfile : Profile
{
    public string Property6 { get; set; } = "8";
}

然后根据类型,可以返回相同的接口/基类。

    public Profile GetPaymentProfile(string aTicketType)
    {
        if (aTicketType == "usePayCore")
            return new PayCorePaymentProfile(); 
        else
            return new PaymentProfile(); 
    }

然后可以使用类型转换来获得实际的实现

    public void ShowProfile1()
    {
        var profile1 = (PayCorePaymentProfile) GetPaymentProfile("usePayCore");
    }

    public void ShowProfile2()
    {
        var profile2 = (PaymentProfile)GetPaymentProfile("other");
    }
© www.soinside.com 2019 - 2024. All rights reserved.