C#使用Dynamic关键字通过字符串访问属性而不反映 [英] C# Using the Dynamic keyword to access properties via strings without reflection

查看:219
本文介绍了C#使用Dynamic关键字通过字符串访问属性而不反映的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写下类似于以下内容的内容:

I would like to write something similar to the following:

//  I will pass in a number of "properties" specified as strings that I want modified
string[] properties = new [] { "AllowEdit", "AllowDelete" };

//  Casting the component I'm using to a dynamic object of some sort ?
dynamic d = myGridComponent;

//  Iterate over the strings and set the properties
foreach(var s in properties) 
{
  //d.s = true; // 
  //d[s] = true; // this format would be ideal
}

我想知道是否有一个简单的方法使用新的C#4.0关键字: .GetProperty(...)。GetValue(...,...)] c>动态。

I was wondering if there was an easy way to do this without using Reflection [.GetProperty(...).GetValue(...,...)] using the new C# 4.0 keyword: dynamic.

似乎可能有一些方法,...我只是不知道确切的机制,无法找到合适的资源把所有的片段放在一起。

It seems that there may be some way, ... I'm just not sure of the exact mechanism, and haven't been able to find the right resource to put all the pieces together.

想法?


看起来有一个名为Clay的包以某种方式实现这种功能。
CodePlex上的粘土

Scott Hanselman主题

推荐答案

可以完成您只需在 DynamicObject 上覆盖 TryGetIndex 。我需要类似的东西来调用类型的静态成员,但希望你会得到这个想法。请注意,您目前无法使用通用类型参数或重载方法,限制其实用程序:

It can be done. You just have to override TryGetIndex on DynamicObject. I needed something similar to invoke static members of a type, but hopefully you will get the idea. Mind you this does not currently work on methods with generic type arguments or methods that are overloaded, limiting its utility:

internal class StaticMembersDynamicWrapper : DynamicObject
{
    private readonly IDictionary<String, MemberInfo> staticMembers = new Dictionary<string, MemberInfo>();
    private readonly Type type;

    public StaticMembersDynamicWrapper(Type type)
    {
        this.type = type;
        type.GetMembers(BindingFlags.FlattenHierarchy | BindingFlags.Static | BindingFlags.Public)
            .Each(member => staticMembers[member.Name] = member);
    }

    public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
    {
        var name = indexes[0] as string;

        MemberInfo member;

        if (false == staticMembers.TryGetValue(name, out member))
        {
            result = null;
            return false;
        }

        var prop = member as PropertyInfo;
        if (prop != null)
        {
            result = prop.GetValue(null, null);
            return true;
        }
        var method = member as MethodInfo;
        if (method != null)
        {
            var parameterTypes = (from p in method.GetParameters()
                                  select p.ParameterType).ToArray();
            var delegateType = method.ReturnType != typeof (void)
                            ? Expression.GetFuncType(parameterTypes.Union(new[]{method.ReturnType}).ToArray())
                            : Expression.GetActionType(parameterTypes);
            result = Delegate.CreateDelegate(delegateType, method);
            return true;
        }
        result = null;
        return false;
    }
}

dynamic d = new StaticMembersDynamicWrapper(typeof(string));
var result = d["IsNullOrEmpty"](String.Empty);

这篇关于C#使用Dynamic关键字通过字符串访问属性而不反映的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆