Этим утром я приступил к быстрому упражнению с использованием пользовательских атрибутов полей. Я перепробовал много вещей и искал много примеров (большинство включало в себя класс, а не атрибуты полей), я официально застрял.
Мой код ниже. Одна особенность заключается в том, что класс создается в FileHelpers с использованием classbuilder. Мои различные частично успешные попытки все же смогли получить имена полей из этого класса, поэтому я считаю, что эта часть работает нормально.
Что я хочу сделать (согласно комментарию в коде): а) пройти через поля, б) для каждого, посмотреть, существует ли атрибут DBDataTypeAttribute, и в), казалось бы, самая трудная часть - получить значения из атрибута (Строка FieldType и AllowNulls bool).
Любые комментарии приветствуются!
Mark
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; }
}
}