カスタム属性を読み取るための式ツリーを持つデリゲートを作成しようとしています。サンプルコードは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()メソッドを使用することができますか?
これは、反射を集中的に使用する実際の方法の簡略版です。反射に基づく欠点を取り除くためにここに代議員を返します。私はしばしば、デリゲートコールのパラメータとしてカスタム属性を持ついくつかのヘルパークラスを使用します。あなたの変更により、上記のコードはうまく動作します。あなたの時間をありがとう。 –