【发布时间】:2010-09-14 05:38:54
【问题描述】:
我有一个专门的列表,其中包含 IThing 类型的项目:
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);
有没有更好、更不臭的方法来做到这一点?
谢谢, 埃里克
编辑:@Matt:.Net 2.0
结论:.Net 2.0(使用 Visual Studio 2005)没有更好的方法。也许我们应该很快迁移到 .Net 3.5 和 Visual Studio 2008。谢谢,伙计们。
结论:有很多不同的方法比反射要好得多。取决于运行时和 C# 版本。看看 Jon Skeets 对差异的回答。所有答案都非常有帮助。
我会寻求 Sklivvz 的建议(匿名方法)。有几个来自其他人(Konrad Rudolph、Matt Hamilton 和 Coincoin)的代码 sn-ps 实现了 Sklivvz 的想法。很遗憾,我只能“接受”一个答案。
非常感谢。你们都可以感到“被接受”,尽管只有 Sklivvz 获得了学分;-)
【问题讨论】:
-
我添加了一个有效的实现
标签: c# .net reflection .net-2.0