从C#中的“自定义字段属性”获取值

问题描述

|| 今天早上,我开始了使用自定义字段属性的快速练习。尝试了很多事情并搜索了许多示例(大多数涉及类而不是字段属性)之后,我正式陷入困境。 我的代码如下。一种特点是该类是使用classbuilder在FileHelpers中构建的。我的各种部分成功的尝试确实设法从此类中获得了字段名,所以我相信这部分工作正常。 我要执行的操作(按代码中的注释)是:a)浏览各个字段,b)每个字段,查看DBDataTypeAttribute属性是否存在,以及c)看似最困难的部分-从属性(FieldType字符串)中获取值,和AllowNulls bool)。 任何意见表示赞赏! 标记
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(\'\"\"\',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; }
    }

}
    

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)