Csharp/C#教程:仅在特定类型上允许自定义属性分享


仅在特定类型上允许自定义属性

有没有办法强制编译器限制自定义属性的使用仅用于特定属性类型,如int,short,string(所有基本类型)?
类似于AttributeUsageAttribute的ValidOn- AttributeTargets枚举。

不,基本上你不能。 你可以将它限制为struct vs class vs interface ,即它。 另外:您无法向代码外部的类型添加属性(除了通过TypeDescriptor ,这是不一样的)。

您可以运行此unit testing来检查它。

首先,声明validation属性PropertyType:

  [AttributeUsage(AttributeTargets.Class)] // [JetBrains.Annotations.BaseTypeRequired(typeof(Attribute))] uncomment if you use JetBrains.Annotations public class PropertyTypeAttribute : Attribute { public Type[] Types { get; private set; } public PropertyTypeAttribute(params Type[] types) { Types = types; } } 

创建unit testing:

  [TestClass] public class TestPropertyType { public static Type GetNullableUnderlying(Type nullableType) { return Nullable.GetUnderlyingType(nullableType) ?? nullableType; } [TestMethod] public void Test_PropertyType() { var allTypes = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes()); var allPropertyInfos = allTypes.SelectMany(a => a.GetProperties()).ToArray(); foreach (var propertyInfo in allPropertyInfos) { var propertyType = GetNullableUnderlying(propertyInfo.PropertyType); foreach (var attribute in propertyInfo.GetCustomAttributes(true)) { var attributes = attribute.GetType().GetCustomAttributes(true).OfType(); foreach (var propertyTypeAttr in attributes) if (!propertyTypeAttr.Types.Contains(propertyType)) throw new Exception(string.Format( "Property '{0}.{1}' has invalid type: '{2}'. Allowed types for attribute '{3}': {4}", propertyInfo.DeclaringType, propertyInfo.Name, propertyInfo.PropertyType, attribute.GetType(), string.Join(",", propertyTypeAttr.Types.Select(x => "'" + x.ToString() + "'")))); } } } } 

例如,您的属性仅允许小数属性类型:

  [AttributeUsage(AttributeTargets.Property)] [PropertyType(typeof(decimal))] public class PriceAttribute : Attribute { } 

示例型号:

 public class TestModel { [Price] public decimal Price1 { get; set; } // ok [Price] public double Price2 { get; set; } // error } 

您可以自己编写代码以强制正确使用属性类,但这与您可以做的一样多。

如果属性放置在不是字符串List的属性/字段上,则下面的代码将返回错误。

if (!(value is List list))可以是C#6或7特征。

上述就是C#学习教程:仅在特定类型上允许自定义属性分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public sealed class RequiredStringListAttribute : ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext context) { if (!(value is List list)) return new ValidationResult($"The required attrribute must be of type List"); bool valid = false; foreach (var item in list) { if (!string.IsNullOrWhiteSpace(item)) valid = true; } return valid ? ValidationResult.Success : new ValidationResult($"This field is required"); ; } } 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1019670.html

(0)
上一篇 2022年1月5日
下一篇 2022年1月5日

精彩推荐