从属性值获取属性
本文关键字:属性 获取 从属性 | 更新日期: 2023-09-27 18:25:21
拥有这个简单的类:
public class Book
{
[DataMember]
[Column("Bok_Name")]
[Author("AuthorName")]
public string Name{ get; set; }
[DataMember]
[Column("Bok_Publisher")]
public string Publisher{ get; set; }
}
在知道属性类型为Column且值为Bok_Name的情况下,如何从属性中获取PropertyInfo。我尝试使用linq查询来完成此操作。
使用反射和.NET扩展CustomAttributeExtensions.GetCustomAttribute{T}方法,可以找到具有自定义属性的属性。在这种情况下,自定义属性来自System.ComponentModel.DataAnnotations.Schema.ColumnAttribute
。
var book = new Book { Name = "Jitterbug Perfume" };
PropertyInfo bokName = typeof(Book)
.GetProperties(BindingFlags.Public | BindingFlags.Instance) // add other bindings if needed
.FirstOrDefault(x => x.GetCustomAttribute<ColumnAttribute>() != null
&& x.GetCustomAttribute<ColumnAttribute>().Name.Equals("Bok_Name", StringComparison.OrdinalIgnoreCase));
// the above query only gets the first property with Column attribute equal to "Bok_Name"
// if there are more than one, then use a .Where clause instead of FirstOrDefault.
if (bokName != null)
{
string name = bokName.GetValue(book).ToString();
// do other stuff
}
var type = typeof (Book); //or var type=instance.GetType();
var res=type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
.Where(
p =>
(p.GetCustomAttribute<ColumnAttribute>() ?? new ColumnAttribute()).Value == "Bok_Name");
在存钱罐中,VBNET上的变体:
Dim maxLength = ValToInt(document.GetDataAnnotationPropertyAttributeValue(fieldName, GetType(MaxLengthAttribute)))
Public Function GetDataAnnotationPropertyAttributeValue(propertyName As String, attributeType As Type) As Object
Dim properties = Me.GetType().GetProperties()
Dim propertyInfo = properties.FirstOrDefault(Function(p) p.Name?.ToLower() = propertyName?.ToLower())
If propertyInfo Is Nothing Then Return Nothing
Dim attribute = propertyInfo.CustomAttributes.FirstOrDefault(Function(a) a.AttributeType.Equals(attributeType))
Return attribute?.ConstructorArguments(0).Value
End Function