对泛型T的属性操作
2010-02-08 12:50 爱研究源码的javaer 阅读(503) 评论(0) 编辑 收藏 举报
代码
public class PropertyHelper<T>
{
private T entiy;
public PropertyHelper(T t)
{ entiy = t;
BindingAttr = BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance;
}
public BindingFlags BindingAttr { get; set; }
public T Entiy { get { return entiy; } }
public object this[string name] { get{ return this[name, null]; } set { this[name,null] = value; }}
public object this[string name,object[] index] { get { if (name == null) throw new ArgumentNullException("name"); object obj = null;
try {
PropertyInfo info = entiy.GetType().GetProperty(name, BindingAttr);
obj = info.GetValue(entiy, index); }
catch (Exception e)
{ throw new Exception(e.Message); }
return obj; }
set { if (name == null) throw new ArgumentNullException("name");
try { PropertyInfo info = entiy.GetType().GetProperty(name, BindingAttr);
info.SetValue(entiy,value,index);
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
}
}
{
private T entiy;
public PropertyHelper(T t)
{ entiy = t;
BindingAttr = BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance;
}
public BindingFlags BindingAttr { get; set; }
public T Entiy { get { return entiy; } }
public object this[string name] { get{ return this[name, null]; } set { this[name,null] = value; }}
public object this[string name,object[] index] { get { if (name == null) throw new ArgumentNullException("name"); object obj = null;
try {
PropertyInfo info = entiy.GetType().GetProperty(name, BindingAttr);
obj = info.GetValue(entiy, index); }
catch (Exception e)
{ throw new Exception(e.Message); }
return obj; }
set { if (name == null) throw new ArgumentNullException("name");
try { PropertyInfo info = entiy.GetType().GetProperty(name, BindingAttr);
info.SetValue(entiy,value,index);
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
}
}
PropertyHelper<BomG> bh = new PropertyHelper<BomG>(bomg);
string name = bh["Name"] as string;
2.string dec = "qazxswedc";
ProPertyHelper<string> dechelper = new PropertyHelper<string>(dec);
int leng = (int)dechelper["Length"] ;