我需要在 C# 中创建一个接口和一个加载接口列表的方法

I need to create an interface in c# and a method to load a list of the interface

有下面两个class/inteface:

[Schema("dbo")]
[Alias("Team")]
public class Team : IHasId<int>
{
    [Alias("TeamId"), AutoIncrement]
    public int Id { get; set;}

    [Required]
    public string TeamName { get; set;}

    [Required]
    public DateTime CreatedOn { get; set;}

    [Required]
    public int DivisionId { get; set; }

    [Required]
    public bool IsActive { get; set; }
}

public interface ITotal
{
    DateTime Date { get; set; }
    Team Team { get; set; }
    Account Account { get; set; }
    double Total { get; set; }
}

public class Total: ITotal
{
    public DateTime Date {get; set;}
    public Team Team {get; set;}
    public Account {get; set;}
    public double Total {get; set;}
}

我正在尝试创建一个默认方法来 return 团队 ID 的总和,我对使用接口不是很熟悉,所以我不确定我所做的是否是最好的解决方案,也我应该使用 ITotalCollection 之类的东西而不是 List 吗?

public class QueryTotalCollection: List<Total>
{
    public List<Total> GetTotalByTeam()
    {
        // todo: I need to return here the same object. However,
        // grouping by Team and the Sum of .Total (in this case the
        // property "Account" will return null as I am grouping by Team.
        // for instance: select Date, Team, null as Account, sum(Total)
        //               group by Date, Team
        // return this.GroupBy(x => x.Team.Id)...
    }
}

上面的方法不行,请问怎么办?我要return一个 ITotal.Total 的总和按 Team.Id

分组

您需要使用您的 类 之一正确实现 ITotal 接口,其中将包括该接口的所有声明方法。像这样:

public class QueryTotalCollection: ITotal
{
    public double Total()
    {
        //your actual method body code.
    }
}

另外,您可能想阅读一些关于 Interfaces 的基本内容以及它们的使用和实施方式。这应该可以帮助您解决这个问题。

希望对您有所帮助。

存在基本的接口误用以及您认为的误用。首先,如果你想创建一个 class 来做 return 总和,那么就这样做。你不需要接口。

但是如果您有多个 class 将实现 ITotal 接口(至少两个),那么我建议使用辅助方法,因为它正是您所需要的(您需要辅助方法吗?)。关于 extending class 的信息。示例代码:

public static class TeamSelectHeleper
{
    public static double GetTotalByTeam(this List<ITotal> myList)
    {
        // TODO Sum wont work this way - fix it
        //return myList.GroupBy(x => x.Team.Id).Sum(s => s.Total);

        // If you need just a sum, then just sum it.
        // but if you need group results,
        // then you can just return on number when there is a list
        return myList.Sum(s => s.Total);
    }
}

然后您可以将此方法应用于任何包含 ITotal 的列表。 group by 并不像您想象的那样工作。使用 stack answer or MSDN