c# - ObservableCollection 和 IEnumerable 的通用方法

标签 c# generics ienumerable

我有这个功能:

public static double MaxValue(IEnumerable<double> Collection)
{
    double max = Collection.First();
    foreach (double d in Collection)
        if (d > max)
            max = d;

    return max;
}
  1. 如果我定义一个泛型方法:MaxValue<T>(IEnumerable<T> Collection)我如何确保没有人可以在没有 < 的情况下在自定义类型上使用它>定义?这是值得担心的好事吗?

  2. 我如何才能编写一种同时适用于 IEnumerable 的方法?和ObservableCollection

最佳答案

If I define a generic method: MaxValue<T>(IEnumerable<T> Collection) how can I assure that no one could use that on a custom type without < > defined? Is this a good thing to be worried of?

如果我理解你的意思,你根本不能使用这里定义的通用方法。如果你愿意,你需要约束 T实现IComparable<T> ,这样您就可以将其与另一个值进行比较,或者采用 IComparer<T>在你的方法中(然后就不需要约束):

public T MaxValue<T>(IEnumerable<T> collection) where T : IComparable<T>
{
    T maxValue = default(T);
    foreach (var element in collection)
    {
        var comparsion = element.CompareTo(maxValue);
        if (comparsion > 0)
            maxValue = element;
    }
    return maxValue;
}

或者

public T MaxValue<T>(IEnumerable<T> collection, IComparer<T> comparer)
{
    T maxValue = default(T);
    foreach (var element in collection)
    {
        var comparsion = comparer.Compare(element, maxValue);
        if (comparsion > 0)
            maxValue = element;
    }
    return maxValue;
}

How can I code just one method that works both for IEnumerable and ObservableCollection?

ObservableCollection<T>实现IEnumerable<T> 。您可以做的是创建一个适用于任何 IEnumerable<T> 的扩展方法。 ,类似于 LINQ通过 System.Linq 工作命名空间:

public static class Extensions
{
    public static T MaxValue<T>(this IEnumerable<T> collection) where T : IComparable<T>
    {
        T maxValue = default(T);
        foreach (var element in collection)
        {
            var comparsion = element.CompareTo(maxValue);
            if (comparsion > 0)
                maxValue = element;
        }
        return maxValue;
    }

    public static T MaxValue<T>(this IEnumerable<T> collection, IComparer<T> comparer)
    {
       T maxValue = default(T);
       foreach (var element in collection)
       {
           var comparsion = comparer.Compare(element, maxValue);
           if (comparsion > 0)
               maxValue = element;
       }
       return maxValue;
    }
}

关于c# - ObservableCollection 和 IEnumerable 的通用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32647364/

相关文章:

c# - 是否可以在 MVVM 模式中使用 WindowsFormsHost?

c# - 需要在 Selenium C# 中使用 EventFiringWebDriver 和 OnFindingElement 或 OnElementClicked 的工作示例?

c# - 如何反序列化具有类字符串值的对象

C# List IList 或 IEnumerable 作为参数

c# - 使类继承构造函数的最简单方法 (C#)

java - Java的通用类型参数命名约定(带有多个字符)?

c# - 通用方法和转换 : how to define that Type 1 is convertible to Type 2

java - Java 中菱形运算符 (<>) 的作用是什么?

c# - 我可以有一个方法返回 IEnumerator<T> 并在 foreach 循环中使用它吗?

c# - IEnumerable<T> 是否存储稍后调用的函数?