{
T Ttype = (T)Activator.CreateInstance(typeof(T));
PropertyInfo[] Tpropertys = Ttype.GetType().GetProperties();
foreach (PropertyInfo tp in Tpropertys)
{
object value = tp.GetValue(Ttype,null);//获取属性的值
tp.SetValue(Ttype, "", null);//给属性赋值
}
}
//返回一个类的特性,或者类中字段的特性,其中ConfigAttribute为自定义特性
private object test1<T>(Expression<Func<T, object>> expr)
{
//如果lambda表达式是属性操作,则返回属性上的标记
if (expr.Body.NodeType == ExpressionType.MemberAccess)
{
MemberExpression body = expr.Body as MemberExpression;
if (body != null)
{
PropertyInfo pi = body.Member as PropertyInfo;
var objs = pi.GetCustomAttributes(typeof(ConfigAttribute), true);
if (objs.Length > 0)
{
ConfigAttribute attr = objs[0] as ConfigAttribute;
return attr;
}
}
}
//如果lambda表达式是参数操作,则返回类上的标记
if (expr.Body.NodeType == ExpressionType.Parameter)
{
ParameterExpression body = expr.Body as ParameterExpression;
var objs = body.Type.GetCustomAttributes(typeof(ConfigAttribute), true);
if (objs.Length > 0)
{
ConfigAttribute attr = objs[0] as ConfigAttribute;
return attr;
}
}
return null;
}
另外要获取比如MVC中DIsplay这样的特性:
private ModelMetadata GetModelMetadata<T>(string PropertyName)//PropertyName是字段属性名称
{
ModelMetadataProvider provider = ModelMetadataProviders.Current;
ModelMetadata containerMetadata = new ModelMetadata(provider, null, () => null, typeof(T), null);
var metadata = containerMetadata.Properties.FirstOrDefault(m => m.PropertyName == PropertyName);
return metadata;
}