0

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

我试图与 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#中是否有类似的东西

4

2 回答 2

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
    }
于 2012-10-30T15:04:26.920 回答
0

您可以使用表达式树来描述表达式,例如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")
于 2012-10-30T14:25:58.397 回答