我有几个分配了属性的类。我最感兴趣的是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; }
}
}
我需要知道是否可以为我的类中的属性编写某种扩展方法来返回FieldLength属性的MaxLength值?
例如。我希望能够写出如下内容......
Users user = new Users();
int lastNameMaxLength = user.LastName.MaxLength();
答案 0 :(得分:2)
不,这是不可能的。您可以在Users
上添加扩展方法:
public static int LastNameMaxLength(this Users user) {
// get by reflection, return
}
答案 1 :(得分:2)
为了节省打字,你可以进一步将Jason的扩展改进为类似的东西。
public static void MaxLength<T>(this T obj, Expression<Func<T, object>> property)
这样它将出现在所有对象上(除非你指定了where T
限制)并且你有一个编译时安全的Property Accessor实现,就像你使用代码一样:
user.MaxLength(u => u.LastName);
答案 2 :(得分:0)
没有。因为您建议的语法返回LastName
属性的值而不是属性本身。
为了检索和使用属性,您需要使用反射,这意味着您需要知道属性本身。
作为一个想法,你可以通过使用LINQ的表达式库来解决这个对象的属性。
您可能会查找的示例语法:
var lastNameMaxLength = AttributeResolver.MaxLength<Users>(u => u.LastName);
其中:
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
}
}
我发现这个类有助于解析表达式中的属性:
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);
}
}
答案 3 :(得分:0)
您可以编写扩展方法,但必须接受PropertyInfo
而不是string
的第一个参数(因为string
本身没有属性。)它会看起来像什么像这样:
public static int GetMaxLength(this PropertyInfo prop)
{
// TODO: null check on prop
var attributes = prop.GetCustomeAttributes(typeof(FieldLengthAttribute), false);
if (attributes != null && attributes.Length > 0)
{
MaxLengthAttribute mla = (MaxLengthAttribute)attributes[0];
return mla.MaxLength;
}
// Either throw or return an indicator that something is wrong
}
然后通过反思获得财产:
int maxLength = typeof(Users).GetProperty("LastName").GetMaxLength();
答案 4 :(得分:0)
那种形式是不可能的。您可以管理的最好的方法是获取lambda表达式,获取与之关联的属性,然后使用反射来获取属性。
int GetMaxLength<T>(Expression<Func<T,string>> property);
并称之为:
GetMaxLength<Users>((u)=>LastName)