ج #: ما الفرق بين typedescriptor.getattributes () و getype () .getCustomatributes؟

StackOverflow https://stackoverflow.com/questions/1833288

  •  11-09-2019
  •  | 
  •  

سؤال

خذ هذين كل من الكود:

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.

أول واحد يعود اثنين من السمات، والثاني يعود واحد.

ما الفرق الذي سيؤدي إلى ذلك؟

هل كانت مفيدة؟

المحلول

من صفحة MSDN على typedescribtor.getattributes:

من أجل إعادة مثيلات متعددة من AttributeUsageAttribute.AllowMultiple سمة من AttributeCollection, ، يجب أن تتجاوز سمة الخاص بك Attribute.TypeId خاصية.

للإجابة على السؤال العام "ما هو الفرق؟": القيم التي تم إرجاعها بواسطة TypeDescriptor يمكن تمديدها في وقت التشغيل، في حين أنهم في Type لا تستطيع. صفحة MSDN التي ربطتها بشرح المزيد.

إذا لم تكن بحاجة إلى هذا النوع من امتداد وقت التشغيل، والطريقة TypeDescriptor مقابض سمات متعددة هي مشكلة، ربما تكون أفضل حالا Type.GetCustomAttributes.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top