Raf*_*off 3 c# custom-attributes
背景: 我有一个自定义类,它代表一个数据库表,每个属性对应一个表列.这些属性可以分为三种方式.
示例:以Person对象为例.
RawDataProperties :(这些列包含来自外部源的原始数据)
公共类人{
#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.但是因为我对自定义属性一无所知,所以我想问一下我是否走上了正确的道路,或者是否还有其他更好的方法可以做到这一点.
注意:所示示例在程序设计方面可能不是最好的,我很清楚继承或拆分该类可以解决这个问题.但这不是我的问题 - 我想知道一个类中的属性是否可以被标记或在某种程度上区分使用自定义类别.
您可以使用自定义属性执行此操作.
[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)
| 归档时间: |
|
| 查看次数: |
761 次 |
| 最近记录: |