首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >仅在特定类型上允许自定义属性

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

Stack Overflow用户
提问于 2018-12-07 05:04:35
回答 2查看 0关注 0票数 0

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

EN

回答 2

Stack Overflow用户

发布于 2018-12-07 13:05:50

不,你不能。你可以将它限制为structvs classvs interface,即它。另外:您无法向代码外部的类型添加属性(除了via TypeDescriptor,这是不一样的)。

票数 0
EN

Stack Overflow用户

发布于 2018-12-07 14:25:23

您可以运行此单元测试来检查它。

首先,声明验证属性PropertyType:

代码语言:javascript
复制
  [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;
        }
    }

创建单元测试:

代码语言:javascript
复制
 [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<PropertyTypeAttribute>();
                    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() + "'"))));
                }
            }
        }
    }

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

代码语言:javascript
复制
 [AttributeUsage(AttributeTargets.Property)]
    [PropertyType(typeof(decimal))]
    public class PriceAttribute : Attribute
    {

    }

示例型号:

代码语言:javascript
复制
public class TestModel  
{
    [Price]
    public decimal Price1 { get; set; } // ok

    [Price]
    public double Price2 { get; set; } // error
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100006245

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档