因此,我正在编写一个C#应用程序,使用.net/c# 4.0,我有一个接受自定义类型和字典的方法。我将其用于各种用途,但由于某种原因,我想不出一种方法来封装逻辑。问题是这一行
if (FastIntParse.FastParse(_dict[_Rule.Key].hourly_data[a].PropertyA) >
_Rule.Value)在另一种用途中,它可能是
if (FastIntParse.FastParse(_dict[_Rule.Key].hourly_data[a].PropertyB) >
_Rule.Value)在各种情况下,唯一不同的是我用来与规则值进行比较的属性。由于某些原因,我想不出重用它的方法,因为我没有传递给某个函数的值,因为值是在函数中派生的。我如何编写一个函数来抽象它需要知道它需要派生和传递哪个值信息,即传递给它需要检查的属性,而不是所述属性的值。
int a;
for (int z= 0;z<=2;z++)
{
a = (z * z) * 24;
for (; (a%24) <= _Rule.AlertEndTime; a++)
{
if (FastIntParse.FastParse(_dict[_Rule.Key].hourly_data[a].PropertyA) >
_Rule.Value)
{
EnqueueRuleTrigger(_Rule);
break;
}
}
}我一直在用适当的属性在需要的地方内联重写这个方法。这显然是相当浪费的,任何改变都需要在许多地方进行。提前感谢
发布于 2012-03-16 18:38:56
您可以使用表达式,然后提取方法中的属性,然后使用反射将其绑定到方法中的对象
class Program
{
static void Main(string[] args)
{
List<PropertyBag> bags = new List<PropertyBag>()
{
new PropertyBag() {Property1 = 1, Property2 = 2},
new PropertyBag() {Property1 = 3, Property2 = 4}
};
Runme(x => x.Property1, bags);
Runme(x => x.Property2, bags);
Console.ReadLine();
}
public static void Runme(Expression<Func<PropertyBag, int>> expression, List<PropertyBag> bags)
{
var memberExpression = expression.Body as MemberExpression;
var prop = memberExpression.Member as PropertyInfo;
bags.ForEach( bag =>
Console.WriteLine(prop.GetValue(bag, null))
);
}
}
public class PropertyBag
{
public int Property1 { get; set; }
public int Property2 { get; set; }
}}
发布于 2012-03-16 20:29:18
为了解决访问不同属性和使用不同布尔函数(<,>,==)的问题,您可以像这样使用委托:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace ConsoleApplication1
{
delegate bool CompareFunction(Fii test, Foo item);
class Program
{
static List<Foo> list = new List<Foo>() {
new Foo() { PropertyA = 0, PropertyB = 9 },
new Foo() { PropertyA = 1, PropertyB = 10 }
};
static Fii test = new Fii() { PropertyA = 1 };
static void Main(string[] args)
{
Bar(list, delegate(Fii item1, Foo item2) { return item2.PropertyA < item1.PropertyA; });
Bar(list, delegate(Fii item1, Foo item2) { return item2.PropertyB > item1.PropertyA; });
Bar(list, delegate(Fii item1, Foo item2) { return item2.PropertyA == item1.PropertyA; });
Console.ReadLine();
}
static void Bar(List<Foo> list, CompareFunction cmp)
{
foreach (Foo item in list)
if (cmp(test, item))
Console.WriteLine("true");
else
Console.WriteLine("false");
}
}
class Foo
{
public int PropertyA { get; set; }
public int PropertyB { get; set; }
}
class Fii
{
public int PropertyA { get; set; }
}
}发布于 2012-03-16 14:30:13
让你的函数接受一个lambda参数并传递给它_ => _.PropertyA,_ => _.PropertyB等:
void CheckAndEnqueueRulesByProperty (Func<YourObject, string> propertyGetter)
{
...
if (FastIntParse.FastParse (propertyGetter (
_dict[_Rule.Key].hourly_data[a])) > _Rule.Value)
{
...
}
...
}如果您有许多类型的对象要用相同的逻辑进行检查,请将此函数设为泛型。
https://stackoverflow.com/questions/9732875
复制相似问题