今天早上我开始了我认为使用自定义字段属性的快速练习。尝试了很多事情并搜索了很多示例(大多数涉及类而不是字段属性),我被正式卡住了。
我的代码如下。一个特点是该类是使用类构建器在 FileHelpers 中构建的。我的各种部分成功的尝试确实设法从这个类中获取了字段名,所以我相信这部分工作正常。
我想要做的(根据代码中的注释)是a)遍历字段,b)查看每个字段是否存在 DBDataTypeAttribute 属性,以及 c)看似最难的部分 - 从属性中获取值(FieldType 字符串, 和 AllowNulls 布尔值)。
任何意见表示赞赏!
标记
class Program
{
static void Main(string[] args)
{
// Desired output:
System.Type userType = null;
userType = ClassBuilder.ClassFromString(@"
public class ExpenseReport
{
[FieldQuoted('""', QuoteMode.OptionalForRead, MultilineMode.AllowForRead)]
[DBDataTypeAttribute(FieldType = ""varchar(1000)"", AllowNulls = true)]
public String UniqueID;
[FieldQuoted('""', QuoteMode.OptionalForRead, MultilineMode.AllowForRead)]
public String ERNum;
}");
object[] attributes;
attributes = userType.GetCustomAttributes(typeof(DBDataTypeAttribute), true);
foreach (Object attribute in attributes)
{
// Would like to be able to ID for each field whether the DBDataTypeAttribute is present, and get the FieldType and AllowNulls Values
DBDataTypeAttribute a = (DBDataTypeAttribute)attribute;
Console.WriteLine("Attribute: ", a.FieldType);
Console.ReadLine();
}
}
}
[AttributeUsage(AttributeTargets.Field)]
public class DBDataTypeAttribute : System.Attribute
{
private string fieldtype;
public string FieldType
{
get { return fieldtype; }
}
private string allownulls;
public string AllowNulls
{
get { return allownulls; }
}
}