gpt4 book ai didi

c# - 如何使用用户定义的标签(自定义属性)区分类属性

转载 作者:行者123 更新时间:2023-11-30 15:02:18 25 4
gpt4 key购买 nike

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

示例:以 Person 对象为例。

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

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

    公共(public)类 Person{

    #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

问题:如何以编程方式区分我的 Person 类中的这三种类型的属性?目标是能够使用 System.Reflection 或其他一些组织构造来循环访问特定类型的属性。伪代码:

foreach(Property prop in Person.GetPropertiesOfType("RealProperty"){
... doSmth(prop);
}

我正在考虑编写自定义属性,并将它们卡在属性上,有点像 taggin。但是由于我对自定义属性一无所知,我想问一下我是否走在正确的道路上,或者是否有任何其他更好的方法来做到这一点。

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

最佳答案

您可以使用自定义属性来做到这一点。

    [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,
}

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

[PropertyType(PropertyType.Meta)]
public int Person_ID;
[PropertyType(PropertyType.Real)]
public string FullName;
[PropertyType(PropertyType.Raw)]
public string Phys_EyeColor;

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

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

关于c# - 如何使用用户定义的标签(自定义属性)区分类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12844389/

25 4 0