12

次のようなものを書きたいと思います。

//  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
}

.GetProperty(...).GetValue(...,...)新しい C# 4.0 キーワードを使用して、Reflection [ ] を使用せずにこれを行う簡単な方法があるかどうか疑問に思っていました: dynamic.

何らかの方法があるようです...正確なメカニズムがわからないだけで、すべてのピースをまとめる適切なリソースを見つけることができませんでした.

考え?

[編集] このタイプの機能を何らかの方法で実装する「Clay」と呼ばれるパッケージがあるようです。 件名に関する CodePlex
Scott Hanselman のクレイ

4

3 に答える 3

6

それはできます。TryGetIndexをオーバーライドする必要がありますDynamicObject。あるタイプの静的メンバーを呼び出すのに似たものが必要でしたが、うまくいけば、あなたはそのアイデアを理解するでしょう。これは現在、ジェネリック型の引数を持つメソッドまたはオーバーロードされているメソッドでは機能せず、その有用性が制限されていることに注意してください。

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);
于 2010-08-13T23:52:51.503 に答える
3

いいえdynamic、C#ではそれを提供していません。あなたの2つの例で:

d.s = true; // this looks for a property or field called "s"
d[s] = true; // this looks for an indexer that matches the string/bool signature

が提供するものと同じコードを書くことはできますが、リフレクションを使用するよりもはるかに困難です。(例のように)リフレクションを使用するか、最適化する必要がある場合は、オプションでまたはのいずれかを介してデリゲートにラップできます。dynamicExpressionDelegate.CreateDelegate

于 2010-05-06T18:37:12.577 に答える
2

nugetを介して利用可能なオープンソースフレームワークImpromptu-interfaceは、dynamicが完全に動的な方法で生成するコードをカプセル化します。dynamicキーワードを使用するほど高速ではありませんが、reflectionよりも高速です

foreach(var s in properties) 
{
  //d.s = true; 
  Impromptu.InvokeSet(d, s, true);
}
于 2011-07-18T19:03:14.553 に答える