0
カスタム属性で装飾されたすべてのプロパティでPropertyDescriptorCollectionを取得する必要があります。問題は、TypeDescriptor.GetPropertiesは、すべての属性のプロパティの完全一致でのみフィルタリングできるため、属性のプロパティの設定に関係なくすべてのプロパティを取得したい場合は、フィルタ配列内のすべての可能性をカバーする必要があります。PropertyDescriptorCollectionをカスタム属性でフィルタリングする
[AttributeUsage(AttributeTargets.Property)]
class FirstAttribute : Attribute
{
public bool SomeFlag { get; set; }
}
そして飾らプロパティを持つクラス:これまでのところ
static void Main(string[] args)
{
var firstPropCollection = TypeDescriptor.GetProperties(typeof(Foo), new Attribute[] {new FirstAttribute()});
Console.WriteLine("First attempt: Filtering by passing an array with a new FirstAttribute");
foreach (PropertyDescriptor propertyDescriptor in firstPropCollection)
{
Console.WriteLine(propertyDescriptor.Name);
}
Console.WriteLine();
Console.WriteLine("Second attempt: Filtering by passing an an array with a new FirstAttribute with object initialization");
var secondPropCollection = TypeDescriptor.GetProperties(typeof(Foo), new Attribute[] { new FirstAttribute {SomeFlag = true} });
foreach (PropertyDescriptor propertyDescriptor in secondPropCollection)
{
Console.WriteLine(propertyDescriptor.Name);
}
Console.WriteLine();
Console.WriteLine("Third attempt: I am quite ugly =(... but I work!");
var thirdCollection = TypeDescriptor.GetProperties(typeof(Foo)).Cast<PropertyDescriptor>()
.Where(p => p.Attributes.Cast<Attribute>().Any(a => a.GetType() == typeof(FirstAttribute)));
foreach (PropertyDescriptor propertyDescriptor in thirdCollection)
{
Console.WriteLine(propertyDescriptor.Name);
}
Console.ReadLine();
}
、唯一の方法私は:
class Foo
{
[First]
public string SomeString { get; set; }
[First(SomeFlag = true)]
public int SomeInt { get; set; }
}
そしてメインここ
は私attribueのコードですそれは3番目の試みですが、より直感的でエレガントな方法があるのだろうかと思います。
出力は次のとおりです。 私が見ることができるのは、最後の試行で両方のプロパティを取得できることだけです。私は私が問題を理解していることは本当にわからない事前
解決策の問題は、PropertyInfo []を使用して情報を取得していることです。私はPropertyDescriptorCollectionを使用する必要があります。なぜなら、条件に一致する各プロパティのPropertyDescriptorが必要なためです。 – taquion
Type.GetPropertiesはPropertyInfoの配列を取得します – taquion
あなたはそうです。私の投稿を編集しました。コード内で反復処理しているコレクションから一致する記述子を取得できます。しかし、どのくらいの頻度でこの関数を呼び出すかによって、どちらの関数がより良い仕事を行うかをベンチマークする必要があります。 – Michael