如何解决从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; }
}
}
解决方法
很简单;您必须从字段而不是类型中获取它们。
foreach( FieldInfo field in userType.GetFields() )
{
DBDataTypeAttribute attribute = (DBDataTypeAttribute)Attribute.GetCustomAttribute(field,typeof(DBDataTypeAttribute));
if( attribute != null )
{
// Do something with it.
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。