如何使用用户定义的标记区分类属性(自定义属性)

Raf*_*off 3 c# custom-attributes

背景: 我有一个自定义类,它代表一个数据库表,每个属性对应一个表列.这些属性可以分为三种方式.

示例:以Person对象为例.

  • MetaProperties :(程序需要的列)
    • Person_ID:在表中用于索引等...
    • UserDefinedType:(UDT),复杂类处理表的写权限.
    • 时间戳:需要在C#DataTables中处理UDT
  • RealProperties :(描述真人的实际特征)
    • 全名
    • 出生日期
    • 出生地
    • 眼睛的颜色
    • 等... (更多)
  • RawDataProperties :(这些列包含来自外部源的原始数据)

    • Phys_EyeColor:直接从物理特征数据库导入的眼睛颜色可能是未知格式,可能与来自其他数据库的条目具有冲突值,或任何其他数据质量问题...
    • HR_FullName:HR文件中给出的全名
    • Web_FullName:从Web表单中获取的全名
    • Web_EyeColor:从网络表单中获取的眼睛颜色
    • 等等...

    公共类人{

    #region MetaProperties
    
    public int Person_ID { get; set; }
    public UserDefinedType UDT { get; set; }
    public DateTime timestamp { get; set; }
    
    #endregion
    
    
    #region RealProperties
    
    public string FullName { get; set; }
    public DateTime DateOfBirth { get; set; }
    public string PlaceOfBirth { get; set; }
    public Color EyeColor { get; set; }
    //...
    
    #endregion
    
    
    #region RawDataProperties
    
    public string Phys_EyeColor { get; set; }
    public string Phys_BodyHeight { get; set; }
    
    public string Web_FullName { get; set; }
    public string Web_EyeColor { get; set; }
    
    public string HR_FullName { get; set; }
    //...
    #endregion
    
    Run Code Online (Sandbox Code Playgroud)

    }

问题:如何在Person类中以编程方式区分这三种类型的属性?目标是能够使用System.Reflection某种其他组织结构迭代某种类型的属性.伪代码:

foreach(Property prop in Person.GetPropertiesOfType("RealProperty"){
... doSmth(prop);
}
Run Code Online (Sandbox Code Playgroud)

我正在考虑编写自定义属性,并将它们挂在属性上,有点像taggin.但是因为我对自定义属性一无所知,所以我想问一下我是否走上了正确的道路,或者是否还有其他更好的方法可以做到这一点.

注意:所示示例在程序设计方面可能不是最好的,我很清楚继承或拆分该类可以解决这个问题.但这不是我的问题 - 我想知道一个类中的属性是否可以被标记或在某种程度上区分使用自定义类别.

Bob*_*son 5

您可以使用自定义属性执行此操作.

    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
    public class PropertyAttribute : System.Attribute
    {
       public PropertyType Type { get; private set; }
       public PropertyAttribute (PropertyType type) { Type = type; }
    }

    public enum PropertyType
    {
       Meta,
       Real,
       Raw,
    }
Run Code Online (Sandbox Code Playgroud)

然后,您可以对每个属性或字段执行此操作:

[PropertyType(PropertyType.Meta)]
public int Person_ID;
[PropertyType(PropertyType.Real)]
public string FullName;
[PropertyType(PropertyType.Raw)]
public string Phys_EyeColor;
Run Code Online (Sandbox Code Playgroud)

然后你可以用类似的东西访问它

foreach (PropertyAttribute attr in this.GetType().GetCustomAttributes(typeof(PropertyAttribute), false))
{
    // Do something based on attr.Type
}
Run Code Online (Sandbox Code Playgroud)