1

私はPropertyInfo次のようにリストをフィルタリングしています:

foreach (PropertyInfo propertyInfo in 
            ClassUtils.GetProperties(patternType).
            Where(pi => pi.GetCustomAttribute<TemplateParamAttribute>() != null).
            OrderBy(pi1 => pi1.GetCustomAttribute<TemplateParamAttribute>().Order))
{
    TemplateParamAttribute attr = propertyInfo.GetCustomAttribute<TemplateParamAttribute>();
...

GetCustomAttributeこれは正しく機能しますが、各反復で 3 回の呼び出しに満足していません。呼び出しの数を減らすGetCustomAttribute(それでも linq を使用する) 方法はありますか?

4

5 に答える 5

3

GetCustomAttribute 呼び出しの数を減らす (それでも linq を使用する) 方法はありますか?

絶対に - 早い段階でプロジェクションを実行してください。ただし、読みやすくするために、foreach ループのに宣言されたクエリでこれを行います。

var query = from property in ClassUtils.GetProperties(patternType)
            let attribute = property.GetCustomAttribute<TemplateParamAttribute>()
            where attribute != null
            orderby attribute.Order
            select new { property, attribute };

foreach (var result in query)
{
    // Use result.attribute and result.property
}
于 2013-01-14T12:55:44.587 に答える
1

次のクエリを使用できますlet。匿名型を宣言するキーワードを使用します。

var select = from propertyInfo in typeof (ClassUtils).GetProperties(patternType)
             let attr = propertyInfo.GetCustomAttribute<TemplateParamAttribute>()
             where attr != null
             orderby attr.Order
             select propertyInfo;
foreach (var propertyInfo in select)
{
    //Operate
}
于 2013-01-14T12:55:20.520 に答える
1

どうですか:

foreach(TemplateParamAttribute attr in
    ClassUtils.GetProperties(patternType).
        Select(pi => pi.GetCustomAttribute<TemplateParamAttribute()).
        Where(pa => pa != null).
        OrderBy(pa.Order))
 {
      // Use attr
 }

ループ内でプロパティと属性の両方にアクセスする必要がある場合は、次のようにします。

foreach(var info in
    ClassUtils.GetProperties(patternType).
        Select(pi => new {prop = pi, attr = pi.GetCustomAttribute<TemplateParamAttribute()}).
        Where(pia => pia.attr != null).
        OrderBy(pia.attr.Order))
 {
      // Use info.prop and info.attr
 }
于 2013-01-14T12:55:40.523 に答える
0

GetCustomAttributeオブジェクト以外に何も使用していない場合propertyInfo:

foreach (TemplateParamAttribute attr in ClassUtils.GetProperties(patternType)
    .Select(pi => pi.GetCustomAttribute<TemplateParamAttribute>())
    .Where(a => a != null)
    .OrderBy(a => a.Order))
{
}
于 2013-01-14T12:54:51.433 に答える
0

複数の呼び出しを避けるために、クエリにGetCustomAttribut新しい範囲変数tpaを導入できます。また、ループで属性のみが必要な場合は、カスタム属性を取得してそれらを反復処理します。

var attributes = from pi in ClassUtils.GetProperties(patternType)
                 let tpa = pi.GetCustomAttribute<TemplateParamAttribute>()
                 where tpa != null 
                 orderby tpa.Order
                 select tpa;

foreach(TemplateParamAttribute attr in attributes)
{
    // ...
}
于 2013-01-14T12:56:32.843 に答える