Rob*_*ers 5 c# extension-methods custom-attributes propertyinfo
我有几个类,分配了属性.我最感兴趣的是FieldLength.MaxLength值.
/// <summary>
/// Users
/// </summary>
[Table(Schema = "dbo", Name = "users"), Serializable]
public partial class Users
{
/// <summary>
/// Last name
/// </summary>
[Column(Name = "last_name", SqlDbType = SqlDbType.VarChar)]
private string _LastName;
[FieldLength(MaxLength=25), FieldNullable(IsNullable=false)]
public string LastName
{
set { _LastName = value; }
get { return _LastName; }
}
}
Run Code Online (Sandbox Code Playgroud)
我需要知道是否可以为我的类中的属性编写某种扩展方法来返回FieldLength属性的MaxLength值?
例如.我希望能够写出如下内容......
Users user = new Users();
int lastNameMaxLength = user.LastName.MaxLength();
Run Code Online (Sandbox Code Playgroud)
不会。因为您建议的语法返回属性的值LastName,而不是属性本身。
为了检索和使用属性,您需要使用反射,这意味着您需要了解属性本身。
作为一种想法,您可以通过使用 LINQ 的表达式库来解析对象的属性,从而巧妙地实现此目的。
您可能会寻找的示例语法:
var lastNameMaxLength = AttributeResolver.MaxLength<Users>(u => u.LastName);
Run Code Online (Sandbox Code Playgroud)
在哪里:
public class AttributeResolver
{
public int MaxLength<T>(Expression<Func<T, object>> propertyExpression)
{
// Do the good stuff to get the PropertyInfo from the Expression...
// Then get the attribute from the PropertyInfo
// Then read the value from the attribute
}
}
Run Code Online (Sandbox Code Playgroud)
我发现此类有助于解析表达式的属性:
public class TypeHelper
{
private static PropertyInfo GetPropertyInternal(LambdaExpression p)
{
MemberExpression memberExpression;
if (p.Body is UnaryExpression)
{
UnaryExpression ue = (UnaryExpression)p.Body;
memberExpression = (MemberExpression)ue.Operand;
}
else
{
memberExpression = (MemberExpression)p.Body;
}
return (PropertyInfo)(memberExpression).Member;
}
public static PropertyInfo GetProperty<TObject>(Expression<Func<TObject, object>> p)
{
return GetPropertyInternal(p);
}
}
Run Code Online (Sandbox Code Playgroud)