无法将类字段加载到子类中

时间:2019-03-14 09:03:21

标签: c# asp.net-web-api asp.net-core asp.net-web-api2

第一步>

public class Catalog
{
    public int CatalogId { get; set; }
    public string CatalogName { get; set; }
    public DateTime? StartDate { get; set; }
    public DateTime? EndDate { get; set; }
    public bool IsDeleted { get; set; }
}

第2步进入模型

public class Catalogs : Catalog { }

public class GetCatalogResponse
{
    public Catalogs Catalogs { get; set; }
}

3RD STEP

var resp = new Models.GetCatalogResponse();

在这种情况下,我无法将目录字段加载到var resp

1 个答案:

答案 0 :(得分:1)

如果您要扩展Catalog类以包括自定义字段,请尝试以下操作:

public class Catalog
{
    public int CatalogId { get; set; }
    public string CatalogName { get; set; }
    public DateTime? StartDate { get; set; }
    public DateTime? EndDate { get; set; }
    public bool IsDeleted { get; set; }
}
public class CatalogExtension : Catalog
{
    public string YourCustomValue { get; set; }

    public CatalogExtension(Catalog catalog)
    {
        CatalogId = catalog.CatalogId;
        CatalogName = catalog.CatalogName;
        StartDate = catalog.StartDate;
        EndDate = catalog.EndDate;
        IsDeleted = catalog.IsDeleted;
        YourCustomValue = "test"
    }

    public CatalogExtension()
    {
        // Assign values however you want
    }
}

然后,可以通过以下方式获取新的CatalogExtension对象:

var resp = new CatalogExtension(catalog);

var resp = new CatalogExtension();