我有一些问题/疑问元数据类型。我有 DLL 帮助程序项目,用于使用 LinqToSQL 从 MS SQL Server 访问数据。我还需要为生成的类 ClientInfoView 添加元数据。我是按照以下方式完成的:
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
namespace DataAPI.LINQToSQL
{
[MetadataType(typeof(ClientInfoViewMetaData))]
public partial class ClientInfoView
{
internal sealed class ClientInfoViewMetaData
{
[Category("Main Data"), DisplayName("Client ID")]
public int ID { get; set; }
[Category("Main Data"), DisplayName("Login")]
public string Login { get; set; }
...
}
}
}
但是当我在运行时检查属性时,我发现ClientInfoView没有任何属性。
你能帮我找出一个错误吗?
因为元数据类型不适用于此类目的,但您可以使用此方法
private bool PropertyHasAttribute<T>(string properyName, Type attributeType)
{
MetadataTypeAttribute att = (MetadataTypeAttribute)Attribute.GetCustomAttribute(typeof(T), typeof(MetadataTypeAttribute));
if (att != null)
{
;
foreach (var prop in Type.GetType(att.MetadataClassType.UnderlyingSystemType.FullName).GetProperties())
{
if (properyName.ToLower() == prop.Name.ToLower() && Attribute.IsDefined(prop,attributeType))
return true;
}
}
return false;
}
你可以这样使用
bool res = PropertyHasAttribute<ClientInfoView>("Login", typeof(DisplayAttribute))
这告诉您类属性登录有或没有 displayattribute ,但如果您需要查找属性值,您可以使用 Attribute.GetCustomAttribute 方法并将其转换为您选择的属性,如显示属性并通过 .Name 读取 Name 属性:)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)