var property = obj.GetType().GetProperty(blockName);

        if (property == null)
        {
            var method = obj.GetType().GetMethod(blockName);

            if (method == null)
                return "[" + blockName + "]";
            else
                return method.Invoke(obj, null).ToString();
        }
        else
            return property.GetValue(obj, null).ToString();

此代码应查找名为blockName的值的属性。如果找到属性,则应返回其值。如果不是,它应该查找名为blockName的值的函数。如果找到,它应该调用它并返回返回值。如果它找不到方法,它应该返回[blockName's value]。
它工作得很好,但我在想办法让它更有效率。我不想将方法转换为属性,也不想将属性转换为方法,因为将来我还会添加参数。你能帮帮我吗?
谢谢。

最佳答案

如果您知道签名(即返回类型和参数),那么Delegate.CreateDelegate可以在这里非常有效地使用:

using System;
using System.Reflection;
class Test
{
    public string Foo(int i)
    {
        return i.ToString();
    }
    static void Main()
    {
        MethodInfo method = typeof(Test).GetMethod("Foo");
        Func<Test, int, string> func = (Func<Test, int, string>)
            Delegate.CreateDelegate(typeof(Func<Test, int, string>), null, method);
        Test t = new Test();
        string s = func(t, 123);

    }
}

注意,对于属性,您需要查看GetGetMethodGetSetMethod。如果您不知道签名,这就不太有效,因为DynamicInvoke非常慢。
要从Delegate.CreateDelegate中获益,必须缓存并重新使用委托实例;不要每次都重新创建它!
对于属性,即使您不知道属性类型,也可以考虑HyperDescriptor(您需要添加1行以启用超描述符):
using System.ComponentModel;
class Test
{
    public int Bar { get; set; }
    static void Main()
    {
        PropertyDescriptor prop = TypeDescriptor.GetProperties(
            typeof(Test))["Bar"];
        Test t = new Test();
        t.Bar = 123;
        object val = prop.GetValue(t);
    }
}

09-25 23:07