2012-04-09 3 views
1

カスタム属性を読み取るための式ツリーを持つデリゲートを作成しようとしています。サンプルコードはMethodCall式を使用してAttribute.GetCustomAttributesを呼び出す

[AttributeUsage(AttributeTargets.Class)] 
public class TestAttribute : Attribute 
{ 
    public string Description { get; set; } 
} 


[TestAttribute(Description="sample text")] 
public class TestClass 
{ 
} 

です。説明プロパティの値をFuncデリゲートで取得したいとします。私は私が

public Func<T, string> CreateDelegate<T>() 
    { 
     //Below is the code which i want to write using expressions 
     //TestAttribute attribute = typeof(T).GetCustomAttributes(typeof(TestAttribute), false)[0]; 
     //return attribute.Description; 

     ParameterExpression clazz = Expression.Parameter(typeof(T),"clazz"); 
     ParameterExpression description = Expression.Variable(typeof(string),"description"); 
     ParameterExpression attribute=Expression.Variable(typeof(TestAttribute),"attribute"); 

     MethodCallExpression getAttributesMethod = Expression.Call(typeof(Attribute).GetMethod("GetCustomAttributes"),clazz); 

     Expression testAttribute = Expression.TypeAs(Expression.ArrayIndex(getAttributesMethod, Expression.Constant(0)), typeof(TestAttribute)); 
     BinaryExpression result = Expression.Assign(description, Expression.Property(testAttribute, "Description")); 

     BlockExpression body = Expression.Block(new ParameterExpression[] { clazz, attribute,description }, 
      getAttributesMethod, testAttribute, result);    

     Func<T, string> lambda = Expression.Lambda<Func<T, string>>(body, clazz).Compile(); 
     return lambda; 
    } 

ような何かを書き込もうとしましたが、私は、このメソッドを呼び出したとき、私はgetAttributesMethodラインでAmbiguousMatchExceptionを取得し、それがあいまいな一致が見つかった「と言うruntime.Soで、このデリゲートを作成する表現でこれをachiveたいです。 "だから私は式ツリー内でAttribute.GetCustomAttribute()メソッドを使用することができますか?

答えて

0

はこれを試してみてください:

MethodCallExpression getAttributesMethod = Expression.Call(typeof(Attribute), 
    "GetCustomAttributes", null, Expression.Constant(typeof(T))); 

しかし、なぜあなたはFunc<T, string>を返すのですか?デリゲートコールのパラメータとしては何を使用しますか?

+0

これは、反射を集中的に使用する実際の方法の簡略版です。反射に基づく欠点を取り除くためにここに代議員を返します。私はしばしば、デリゲートコールのパラメータとしてカスタム属性を持ついくつかのヘルパークラスを使用します。あなたの変更により、上記のコードはうまく動作します。あなたの時間をありがとう。 –

0

ここは実際にリフレクションのこのブロックです:そこのオーバーロードがあり、あなたは、パラメータの型を指定しない場合

typeof(Attribute).GetMethod("GetCustomAttributes") 

GetMethodは、その例外がスローされます。

試してみてください。

typeof(Attribute).GetMethod("GetCustomAttributes", new [] {typeof(MemberInfo)}) 
+0

今回は例外がArgumentExceptionに変更されました。パフ私は本当に立ち往生した。 –

+0

@OlcaySekerコードを実行できるように、あなたの質問に「間違い」を置き換えることはできますか? – vcsjones

+0

OKがより明確になるように変更されました。 –

関連する問題