访问新的类对象的属性

时间:2017-03-22 15:18:02

标签: c#

如果我正在创建一个新的类对象并分配其属性值,如下所示:

foreach (var item in lstOfPersonnel)
{
    ClassNameVM personVM = new ClassNameVM ()
    {
        Name = item.FirstName + " " + item.LastName,
        TimeTotalPFID = lstSummaries.Where(x => x.PFID == item.ID).Sum(x => x.Time),
        TimeTotalPNFID = lstSummaries.Where(x => x.PNFID == item.ID).Sum(x => x.Time),
        TimeTotalVO = lstSummaries.Where(x => x.VO == item.ID).Sum(x => x.Time),
        TotalTime = // trying to do TimeTotalPFID + TimeTotalPNFID + TimeTotalVO.. but I can't access those properties.
    };

    newListPersonnel.Add(personVM);
}

如何访问对象内的TimeTotalPFIDTimeTotalPNFIDTimeTotalVO属性?

3 个答案:

答案 0 :(得分:6)

您无法访问这些属性,因为它们在该匿名对象调用的范围内在技术上不存在。

考虑在声明下面的行上设置该属性:

ClassNameVM personVM = new ClassNameVM ()
{
    Name = item.FirstName + " " + item.LastName,
    TimeTotalPFID = lstSummaries.Where(x => x.PFID == item.ID).Sum(x => x.Time),
    TimeTotalPNFID = lstSummaries.Where(x => x.PNFID == item.ID).Sum(x => x.Time),
    TimeTotalVO = lstSummaries.Where(x => x.VO == item.ID).Sum(x => x.Time),
};

// Set your properties here
personVM.TotalTime = personVm.TimeTotalPFID + personVM.TimeTotalPNFID + personVM.TimeTotalVO;

考虑一个构造函数

或者,您可以定义一个构造函数,该构造函数将接受item类型的参数并使用它:

public ClassNameVM(YourItemType item)
{
    Name = item.FirstName + " " + item.LastName;
    TimeTotalPFID = lstSummaries.Where(x => x.PFID == item.ID).Sum(x => x.Time);
    TimeTotalPNFID = lstSummaries.Where(x => x.PNFID == item.ID).Sum(x => x.Time);
    TimeTotalVO = lstSummaries.Where(x => x.VO == item.ID).Sum(x => x.Time);
    TotalTime = TimeTotalPFID + TimeTotalPNFID + TimeTotalVO;
}

这将使您更容易使用:

foreach (var item in lstOfPersonnel)
{
    newListPersonnel.Add(new ClassNameVM(item));
}

答案 1 :(得分:3)

最简单的解决方案是:

ClassNameVM personVM = new ClassNameVM ()
        {
            Name = item.FirstName + " " + item.LastName,
            TimeTotalPFID = lstSummaries.Where(x => x.PFID == item.ID).Sum(x => x.Time),
            TimeTotalPNFID = lstSummaries.Where(x => x.PNFID == item.ID).Sum(x => x.Time),
            TimeTotalVO = lstSummaries.Where(x => x.VO == item.ID).Sum(x => x.Time),

        };
      personVM.TotalTime = personVM.TimeTotalPFID + personVM.TimeTotalPNFID + personVM.TimeTotalVO;

答案 2 :(得分:1)

在这种情况下,如果您希望总时间只是其他属性的总和,那么每次都不要用它。这很容易出错,如果其他属性发生变化,则无法正确响应。在这种情况下,最好只有一个只有get的属性才能为你计算...

public class ClassNameVM
{
    /*other properties as normal */
    public int TotalTime
    {
        get { return TimeTotalPFID + TimeTotalPNFID + TimeTotalVO; }
    }
}