我有持有IThing
類型的項目一個專門的列表:C#:獲取的所有項目的任意屬性的最大值和最小值在列表
public class ThingList : IList<IThing>
{...}
public interface IThing
{
Decimal Weight { get; set; }
Decimal Velocity { get; set; }
Decimal Distance { get; set; }
Decimal Age { get; set; }
Decimal AnotherValue { get; set; }
[...even more properties and methods...]
}
有時候,我需要知道一定的最大值或最小值屬性列表中的所有東西。由於「告訴不問」我們讓列表圖出來:
public class ThingList : IList<IThing>
{
public Decimal GetMaximumWeight()
{
Decimal result = 0;
foreach (IThing thing in this) {
result = Math.Max(result, thing.Weight);
}
return result;
}
}
那是非常好的。但有時候我需要最小的重量,有時候最大的速度等等。我不想爲每個物業配對GetMaximum*()/GetMinimum*()
。
一個解決方案是反射。類似的東西(保持你的鼻子,強烈的代碼氣味!):
Decimal GetMaximum(String propertyName);
Decimal GetMinimum(String propertyName);
有沒有更好的,少臭的方法來實現這一目標?
感謝, 埃裏克
編輯:@馬特:NET 2.0
結論:對於.NET 2.0沒有更好的辦法(與Visual Studio 2005)。也許我們應該儘快轉向.NET 3.5和Visual Studio 2008。多謝你們。
結論:有不同的方法比反思好得多。取決於運行時和C#版本。看看Jon Skeets對差異的回答。所有的答案都是非常有幫助的。
我會去Sklivvz的建議(匿名方法)。來自其他人(Konrad Rudolph,Matt Hamilton和Coincoin)的幾個代碼片段實現了Sklivvz的想法。不幸的是,我只能「接受」一個答案。
非常感謝。你可以都覺得「接受」,僅altough得到Sklivvz學分;-)
我已經添加了一個工作實現 – Sklivvz 2008-09-30 23:56:40