我对泛型和反射的经验非常少。我从以下示例中假设是执行需要花费太多时间。有没有办法让我在不使用反射的情况下完成以下操作..
场景我正在研究一种通用的方法。它接受一个传递给它的类的实例,并从所有属性中生成 SqlParameters。以下是名为“Store”的泛型方法的代码,以及另一种将 c# 类型转换为 DbType 的 SqlDbType 的方法。
List<SqlParameter> parameters = new List<SqlParameter>();
public T Store<T>(T t)
{
Type type = t.GetType();
PropertyInfo[] props = (t.GetType()).GetProperties();
foreach (PropertyInfo p in props)
{
SqlParameter param = new SqlParameter();
Type propType = p.PropertyType;
if (propType.BaseType.Name.Equals("ValueType") || propType.BaseType.Name.Equals("Array"))
{
param.SqlDbType = GetDBType(propType); //e.g. public bool enabled{get;set;} OR public byte[] img{get;set;}
}
else if (propType.BaseType.Name.Equals("Object"))
{
if (propType.Name.Equals("String"))// for string values
param.SqlDbType = GetDBType(propType);
else
{
dynamic d = p.GetValue(t, null); // for referrences e.g. public ClassA obj{get;set;}
Store<dynamic>(d);
}
}
param.ParameterName = p.Name;
parameters.Add(param);
}
return t;
}
// mehthod for getting the DbType OR SqlDbType from the type...
private SqlDbType GetDBType(System.Type type)
{
SqlParameter param;
System.ComponentModel.TypeConverter tc;
param = new SqlParameter();
tc = System.ComponentModel.TypeDescriptor.GetConverter(param.DbType);
if (tc.CanConvertFrom(type))
{
param.DbType = (DbType)tc.ConvertFrom(type.Name);
}
else
{
// try to forcefully convert
try
{
param.DbType = (DbType)tc.ConvertFrom(type.Name);
}
catch (Exception e)
{
switch (type.Name)
{
case "Char":
param.SqlDbType = SqlDbType.Char;
break;
case "SByte":
param.SqlDbType = SqlDbType.SmallInt;
break;
case "UInt16":
param.SqlDbType = SqlDbType.SmallInt;
break;
case "UInt32":
param.SqlDbType = SqlDbType.Int;
break;
case "UInt64":
param.SqlDbType = SqlDbType.Decimal;
break;
case "Byte[]":
param.SqlDbType = SqlDbType.Binary;
break;
}
}
}
return param.SqlDbType;
}
调用我的方法假设我有 2 个类如下
public class clsParent
{
public int pID { get; set; }
public byte[] pImage { get; set; }
public string pName { get; set; }
}
and
public class clsChild
{
public decimal childId { get; set; }
public string childName { get; set; }
public clsParent parent { get; set; }
}
and this is a call
clsParent p = new clsParent();
p.pID = 101;
p.pImage = new byte[1000];
p.pName = "John";
clsChild c = new clsChild();
c.childId = 1;
c.childName = "a";
c.parent = p;
Store<clsChild>(c);