比较短语的反映

时间:2012-10-30 13:58:55

标签: c# reflection parameters comparison phrase

也许我的问题很奇怪......我想知道是否可以对短语使用反思。

我尝试与C#中的反射进行比较。到目前为止,我将属性的名称作为字符串传递,将值作为对象传递,如:Cmp("foo", "abc") 这样我就要检查foo是否是类中的现有属性,并检查值类型是否与属性类型匹配(在上面的示例中,foo是字符串属性,值是字符串)。这样工作正常!

我只是想知道是否可以将短语作为参数发送并用反射或类似的东西进行分析 我的意思是,如上例所示,而不是像Cmp("foo", "abc")那样调用函数,只需调用此函数Cmp(A.foo == "abc")A是具有foo属性的类),然后分析该属性为foo且值为"abc"

我知道它听起来很奇怪,对我来说并不是必需的。它只是为了这个想法 有可能吗?

修改
如果我不清楚,我已经写了Cmp(string, string)方法,它工作正常! 我只是想知道是否有办法编写Cmp方法,如下所示:Cmp(A.foo == "abc")。该参数是一个短语。

编辑2
例如,您可以在C中执行类似的操作。您可以像这样创建宏:

#define Cmp(phrase) printf(##phrase)

然后,如果您将其称为Cmp(A.foo == "abc"),则输出将为:

  

A.foo ==“abc”

将整个短语作为参数传递并进行分析。我知道宏是预编译的东西,我只是想知道C#中是否有类似的东西。

2 个答案:

答案 0 :(得分:0)

您可以使用expression trees来描述bar.Foo == "abc"这样的表达式。这是一个简单的示例,假设您有一个名为Bar的类,其具有名为Foo的属性:

String FormatExpression<T>(Expression<Func<T, Boolean>> expression) {
  if (expression == null)
    throw new ArgumentNullException("expression");
  var body = expression.Body as BinaryExpression;
  if (body == null)
    throw new ArgumentException(
      "Expression body is not a binary expression.", "expression");
  return body.ToString();
}

调用

FormatExpression((Bar bar) => bar.Foo == "abc")

将返回字符串

(bar.Foo == "abc")

答案 1 :(得分:0)

此扩展方法遍历调用它的对象的所有(可读,公共)属性,检查该属性上具有给定名称的属性并比较这些值。

public static class CmpExtension
{
    public static bool Cmp<T, TValue>(this T obj, string propertyName, TValue value)
        where TValue : class
    {
        var properties = obj.GetType().GetProperties()
                .Where(p => p.CanRead);

        foreach (var property in properties)
        {
            var propertyValue = property.GetValue(obj, null);

            var childProperty = property.PropertyType.GetProperties()
                .Where(p => p.CanRead)
                .FirstOrDefault(p => p.Name == propertyName);

            if (childProperty == null) continue;

            var childPropertyValue = childProperty.GetValue(propertyValue, null);

            return childPropertyValue == value;
        }

        return false;
    }
}

通过使用它,您可以:

public class Foo
{
    public Bar Bar { get; set; }
}

public class Bar
{
    public string Value { get; set; }
}

public static void Main(string[] args)
{
    var foo = new Foo { Bar = new Bar { Value = "Testing" } };
    foo.Cmp("Value", "Testing"); // True
}

要使用替代语法,请使用:

public static class CmpExtension
{
    public static bool Cmp<T>(this T obj, Func<T, bool> func)
    {
        return func(obj);
    }
}

使用此功能,您可以

    public static void Main(string[] args)
    {
        var foo = new Foo { Bar = new Bar { Value = "Testing" } };
        foo.Cmp(f => f.Bar.Value == "Testing"); // True
    }