C# 从构造函数中的 REST 客户端初始化类属性



我已经搜索了很多,我认为这是可能的,但我觉得我只是不知道如何正确格式化它。

我有一个代表产品的类,该产品是从我们的CRM到Magento的关系类。

在构造函数中,我必须做一些这样的事情......

public Product(IBaseProduct netforumProduct, MagentoClient client)
{
Product existingMagentoProduct = client.GetProductBySku(netforumProduct.Code);
if (existingMagentoProduct != null)
{
this.id = existingMagentoProduct.id;
this.name = existingMagentoProduct.name;
... many of them ...
this.visibility = existingMagentoProduct.visibility;
this.extension_attributes.configurable_product_links = existingMagentoProduct.extension_attributes.configurable_product_links;
}
else
{
//  its a new product, new up the objects
this.id = -1;
this.product_links = new List<ProductLink>();
this.options = new List<Option>();
this.custom_attributes = new List<CustomAttribute>();
this.media_gallery_entries = new List<MediaGalleryEntry>();
this.extension_attributes = new ExtensionAttributes();
this.status = 0; // Keep all new products disabled so they can be added to the site and released on a specific day (this is a feature, not an issue / problem).
this.attribute_set_id = netforumProduct.AttributeSetId;
this.visibility = 0;
}
}

必须像这样初始化所有属性似乎很愚蠢。 我可以使用映射器,但这似乎是创可贴。我必须首先查看产品是否存在于 magento 中,并填充其 ID 和值,否则每当我保存产品时,它都会创建一个额外的产品。

我考虑过调用静态方法的类构造函数,但我无法获得正确的语法。

可能为时已晚,我需要考虑一段时间其他事情。

如果你必须在构造函数中执行此操作,你可以通过首先将"默认"值设置为"产品"属性来摆脱大量代码。这将消除在构造函数中执行它们的需要。接下来,如果要自动设置类的属性,可以使用反射。

public class Product
{
public int Id { get; set; } = -1;
public List<ProductLink> Product_Links { get; set; } = new List<ProductLink>();
....
public int Visibility { get; set; } = 0;
public Product(IBaseProduct netforumProduct, MagentoClient client)
{
var existingMagentoProduct = client.GetProductBySku(netforumProduct.Code);
if (existingMagentoProduct != null)
{
foreach (PropertyInfo property in typeof(Product).GetProperties().Where(p => p.CanWrite))
{
property.SetValue(this, property.GetValue(existingMagentoProduct, null), null);
}
}
}   
}

不过,我想指出的是,您可能不应该在类构造函数中使用 REST 客户端,尤其是只填充其数据(此外,您正在执行同步操作(。让另一个层负责使用客户端填充此类,然后使用 AutoMapper 之类的东西将数据映射到它,会更干净。

最新更新