如何扩展现有的第三方模型?

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

我正在使用一个第三方库。他们提供了一些类供我用来将数据从一个页面传输到另一个页面,但我没有源代码来进行更改,例如

public class Customer

{

    public string Name {get;set}

    public Additional AdditionalDetails {get;set}

}

在此示例中,我想扩展

Additional
类并向其添加属性,而不破坏现有的工作。

我的控制器和视图通过传入

customer
类来工作,但我想做的就是向
Additional
类添加一个新属性。

我尝试创建一个部分类,但没有成功并收到警告带有单个部分的部分类

然后我尝试将类创建为

public class Additional

在我的项目中的相同的命名空间下并添加新属性,但这也不起作用(属性没有显示)。

有没有办法让我在不破坏现有代码的情况下扩展这个

Additional
类?

c# asp.net-core model-view-controller
2个回答
0
投票

您可以创建一个新类,其中包含附加类的实例并添加您需要的额外属性。这样,您就可以避免直接修改现有的类。

public class AdditionalExtended
{
    public Additional AdditionalDetails { get; set; }
    public string NewProperty { get; set; }
}

然后,更新您的 Customer 类以使用 AnotherExtended 类:

public class Customer
{
    public string Name { get; set; }
    public AdditionalExtended AdditionalDetailsExtended { get; set; }
}

您需要更新代码以使用AdditionalDetailsExtended 属性而不是AdditionalDetails 属性。


0
投票

有没有办法让我在不中断的情况下扩展这个附加课程 现有代码?

为了扩展

Additional class
并为其添加属性而不破坏现有的工作方式,我们可以遵循几种方法,其中一种方法可能是
Wrapper Class

此方法允许您继续使用现有的第三方类(客户和附加),而无需对其用法进行任何修改,同时向附加添加新属性。

首先,我将使用现有详细信息创建一个客户,然后需要包装附加详细信息,其中将包含新的属性,最后构建视图模型以将数据传递到视图。

让我们看看实践:

现有班级:

public class Additional
{
    public string ExistingProperty { get; set; }
}


public class Customer
{
    public string Name { get; set; }
    public Additional AdditionalDetails { get; set; }
}


public interface IAdditional
{
    string ExistingProperty { get; }
}

包装类:

public class ExtendedAdditional : IAdditional
{
    private readonly Additional _original;

    public ExtendedAdditional(Additional original)
    {
        _original = original ?? throw new ArgumentNullException(nameof(original));
    }

    public string ExistingProperty => _original.ExistingProperty;

    public string NewProperty { get; set; }
}

查看型号:

public class CustomerViewModel
{
    public Customer Customer { get; set; }
    public ExtendedAdditional ExtendedAdditional { get; set; }
}

控制器:

public IActionResult Index()
 {
     
     var customer = new Customer
     {
         Name = "Kiron Test",
         AdditionalDetails = new Additional { ExistingProperty = "Existing Value" }
     };

    
     var extendedAdditional = new ExtendedAdditional(customer.AdditionalDetails)
     {
         NewProperty = "New Value"
     };

     
     var model = new CustomerViewModel
     {
         Customer = customer,
         ExtendedAdditional = extendedAdditional
     };

     return View(model);
 }

查看:

@model CustomerViewModel

<h2>Customer Details</h2>
<p>Name: @Model.Customer.Name</p>

<h3>Additional Details</h3>
<p>Existing Property: @Model.ExtendedAdditional.ExistingProperty</p>
<p>New Property: @Model.ExtendedAdditional.NewProperty</p>

输出:

enter image description here

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.