在SCM 项目中用到的一点反射的例子,
//通过传过来对象,和一个字段名,返回在这个对象中的此字段的值,
private string getProperties<T>(T t, string keyName)
{
string tStr = string.Empty;
if (t == null)
{
return tStr;
}
System.Reflection.PropertyInfo[] properties = t.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
if (properties.Length <= 0)
{
return tStr;
}
foreach (System.Reflection.PropertyInfo item in properties)
{
string name = item.Name;
object value = item.GetValue(t, null);
if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String"))
{
if (name == keyName)
{
tStr = value.ToString();
return tStr;
}
//tStr += string.Format("{0}:{1},", name, value);
}
else
{
getProperties(value, keyName);
}
}
return tStr;
}
//这个方法,用来,通过传对象,参数的列名集合,存储过程,自动返回DataSet
#region 用于查询的通用方法,返回DataSet
public DataSet GetDataSet(string proName, string[] listName, object o)
{
try
{
SqlParameter[] paras = null;
if (listName != null)//判断是否传了参数
{
int len = listName.Length;
paras = new SqlParameter[len];
for (int i = 0; i < len; i++)
{
SqlParameter para = GetAllSqlParameter(o, listName[i]);//用来得到参数
paras[i] = para;
}
}
DataSet ds = SQLHelper.GetDataSet(proName, paras);
return ds;
}
catch (Exception ex)
{
throw ex;
}
}
//返回构建的Sqlparameter
private SqlParameter GetAllSqlParameter<T>(T t, string keyName)
{
SqlParameter para = null;
System.Reflection.PropertyInfo[] properties = t.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
foreach (System.Reflection.PropertyInfo item in properties)
{
string name = item.Name;
object value = item.GetValue(t, null);
if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String"))
{
if (name == keyName)
{
para = new SqlParameter("@" + name, ReplaceChar(value.ToString()));
}
}
}
return para;
}