Bri*_*ian 5 .net c# reflection attributes
我试图使用反射来检查给定类上的属性是否设置了ReadOnly属性.我使用的类是MVC视图模型(使用元数据的部分"伙伴"类.
public partial class AccountViewModel
{
public virtual Int32 ID { get; set; }
public virtual decimal Balance { get; set; }
}
[MetadataType(typeof(AccountViewModelMetaData))]
public partial class AccountViewModel
{
class AccountViewModelMetaData
{
[DisplayName("ID")]
public virtual Int32 ID { get; set; }
[DisplayName("Balance")]
[DataType(DataType.Currency)]
[ReadOnly(true)]
public virtual decimal Balance { get; set; }
}
}
Run Code Online (Sandbox Code Playgroud)
我想检查"Balance"是否具有ReadOnly属性.如果我在AccountViewModel的Balance属性上设置ReadOnly属性,我可以这样检索它:
Type t = typeof(AccountViewModel);
PropertyInfo pi = t.GetProperty("Balance");
bool isReadOnly = ReadOnlyAttribute.IsDefined(pi,typeof( ReadOnlyAttribute);
Run Code Online (Sandbox Code Playgroud)
如果它位于元数据类中,我无法检索属性信息.如何检查属性是否存在?我为所有视图模型定义了元数据类,并且需要通用的方法来检查元数据类的属性.
有什么建议?
解决方案是使用GetCustomAttributes获取MetaData类型并检查那些属性...
Type t = typeof(MyClass);
PropertyInfo pi = t.GetProperty(PropertyName);
bool isReadOnly = ReadOnlyAttribute.IsDefined(pi, typeof(ReadOnlyAttribute));
if (!isReadOnly)
{
//check for meta data class.
MetadataTypeAttribute[] metaAttr = (MetadataTypeAttribute[])t.GetCustomAttributes(typeof(MetadataTypeAttribute),true);
if (metaAttr.Length > 0)
{
foreach (MetadataTypeAttribute attr in metaAttr)
{
t = attr.MetadataClassType;
pi = t.GetProperty(PropertyName);
if (pi != null) isReadOnly = ReadOnlyAttribute.IsDefined(pi, typeof(ReadOnlyAttribute));
if (isReadOnly) break;
}
}
}
Run Code Online (Sandbox Code Playgroud)
下面是一个简短但有效的示例,请注意,我创建了嵌套类internal,以便对外部可见。
public partial class AccountViewModel
{
internal class AccountViewModelMetaData
{
public virtual Int32 ID { get; set; }
[ReadOnlyAttribute(false)]
public virtual decimal Balance { get; set; }
}
public virtual Int32 ID { get; set; }
public virtual decimal Balance { get; set; }
}
class Program
{
public static void Main(string[] args)
{
Type metaClass = typeof(AccountViewModel.AccountViewModelMetaData);
bool hasReadOnlyAtt = HasReadOnlyAttribute(metaClass, "Balance");
Console.WriteLine(hasReadOnlyAtt);
}
private static bool HasReadOnlyAttribute(Type type, string property)
{
PropertyInfo pi = type.GetProperty(property);
return ReadOnlyAttribute.IsDefined(pi, typeof(ReadOnlyAttribute));
}
}
Run Code Online (Sandbox Code Playgroud)
另请注意,这会检查该属性是否存在。您可以在此示例中指定属性但提供 的值false。如果你想检查属性是否是只读的,你不能只使用方法ReadOnlyAttribute.IsDefined。