C#の:TypeDescriptor.GetAttributes()およびメソッドGetType().GetCustomAttributesの違いは何ですか?
-
11-09-2019 - |
質問
これらの2つのコードのものを取ります:
instance.GetType()
.GetCustomAttributes(true)
.Where(item => item is ValidationAttribute);
と
TypeDescriptor.GetAttributes(instance)
.OfType<ValidationAttribute>();
クラスがどのように見える場合:
[RequiredIfOtherPropertyIsNotEmpty("State", "City", ErrorMessage = ErrorDescription.CreateAccount_CityRequiredWithState)]
[RequiredIfOtherPropertyIsNotEmpty("State", "Address1", ErrorMessage = ErrorDescription.CreateAccount_Address1RequiredWithState)]
public class ManagePostModel
{
...
}
RequiredIfOtherPropertyIsNotEmpty
がValidationAttribute
あるとAllowMultiple = true
を持っています。
最初の2つの属性、第二戻りいずれかを返します。
これを引き起こすの違いは何でしょうか。
解決
から>:
AttributeUsageAttribute.AllowMultiple
からAttributeCollection
属性の複数のインスタンスを返すためには、あなたの属性はAttribute.TypeId
プロパティをオーバーライドする必要があります。
TypeDescriptor
のものができないのに対し、Type
によって返される値は、実行時に拡張することができます。一般的な質問「?何が違います」と答えるために。私がリンクされMSDNのページには、より多くを説明します。
あなたはランタイム拡張のこの種を必要としない、とTypeDescriptor
は複数の属性を処理する方法に問題がある、あなたはType.GetCustomAttributes
とオフおそらく優れている場合。
所属していません StackOverflow