我有这个功能:
public static double MaxValue(IEnumerable<double> Collection)
{
double max = Collection.First();
foreach (double d in Collection)
if (d > max)
max = d;
return max;
}
如果我定义一个泛型方法:
MaxValue<T>(IEnumerable<T> Collection)
我如何确保没有人可以在没有<
的情况下在自定义类型上使用它>
定义?这是值得担心的好事吗?我如何才能编写一种同时适用于
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/