替代反思

本文关键字: | 更新日期: 2023-09-27 17:54:59

我在泛型和反射方面的经验很少。从下面的示例中,我认为执行它需要花费太多时间。有没有一种方法可以让我在不使用反射的情况下完成以下任务?

场景我正在研究一种通用的方法。它接受传递给它的类的一个实例,并从所有属性中生成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;
        }

调用我的方法假设我有两个类如下

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);

替代反思

如果你想摆脱反射,你可能会在下面的代码中找到灵感。

在这里,所有对存储在数据库中的对象的访问以及sql属性值的赋值都由从数据类型构建的运行时编译表达式处理。

假定保存这些值的表为test,并且假定字段名与属性值相同。

对于每个性质构造一个Mapping<T>。它将保存一个包含数据库字段的FieldName,一个应该被正确插入到SQL INSERT语句中的SqlParameter(在main中的示例),最后如果包含编译的动作,可以采用输入T对象的实例并将值分配给SqlParameters属性Value。这些映射集合的构造在Mapper<T>类中完成。为了便于解释,代码被内联。

最后,main方法显示了如何将这些东西绑定在一起。

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
namespace ExpTest
{
    class Program
    {
        public class Mapping<T>
        {
            public Mapping(string fieldname, SqlParameter sqlParameter, Action<T, SqlParameter> assigner)
            {
                FieldName = fieldname;
                SqlParameter = sqlParameter;
                SqlParameterAssignment = assigner;
            }
            public string FieldName { get; private set; }
            public SqlParameter SqlParameter { get; private set; }
            public Action<T, SqlParameter> SqlParameterAssignment { get; private set; }
        }
        public class Mapper<T>
        {
            public IEnumerable<Mapping<T>> GetMappingElements()
            {
                foreach (var reflectionProperty in typeof(T).GetProperties())
                {
                    // Input parameters to the created assignment action
                    var accessor = Expression.Parameter(typeof(T), "input");
                    var sqlParmAccessor = Expression.Parameter(typeof(SqlParameter), "sqlParm");
                    // Access the property (compiled later, but use reflection to locate property)
                    var property = Expression.Property(accessor, reflectionProperty);
                    // Cast the property to ensure it is assignable to SqlProperty.Value 
                    // Should contain branching for DBNull.Value when property == null
                    var castPropertyToObject = Expression.Convert(property, typeof(object));

                    // The sql parameter
                    var sqlParm = new SqlParameter(reflectionProperty.Name, null);
                    // input parameter for assignment action
                    var sqlValueProp = Expression.Property(sqlParmAccessor, "Value");
                    // Expression assigning the retrieved property from input object 
                    // to the sql parameters 'Value' property
                    var dbnull = Expression.Constant(DBNull.Value);
                    var coalesce = Expression.Coalesce(castPropertyToObject, dbnull);
                    var assign = Expression.Assign(sqlValueProp, coalesce);
                    // Compile into action (removes reflection and makes real CLR object)
                    var assigner = Expression.Lambda<Action<T, SqlParameter>>(assign, accessor, sqlParmAccessor).Compile();
                    yield return
                        new Mapping<T>(reflectionProperty.Name, // Table name
                            sqlParm, // The constructed sql parameter
                            assigner); // The action assigning from the input <T> 
                }
            }
        }
        public static void Main(string[] args)
        {
            var sqlStuff = (new Mapper<Data>().GetMappingElements()).ToList();
            var sqlFieldsList = string.Join(", ", sqlStuff.Select(x => x.FieldName));
            var sqlValuesList = string.Join(", ", sqlStuff.Select(x => '@' + x.SqlParameter.ParameterName));
            var sqlStmt = string.Format("INSERT INTO test ({0}) VALUES ({1})", sqlFieldsList, sqlValuesList);
            var dataObjects = Enumerable.Range(1, 100).Select(id => new Data { Foo = 1.0 / id, ID = id, Title = null });
            var sw = Stopwatch.StartNew();
            using (SqlConnection cnn = new SqlConnection(@"server=.'sqlexpress;database=test;integrated security=SSPI"))
            {
                cnn.Open();
                SqlCommand cmd = new SqlCommand(sqlStmt, cnn);
                cmd.Parameters.AddRange(sqlStuff.Select(x => x.SqlParameter).ToArray());
                dataObjects.ToList()
                    .ForEach(dto =>
                        {
                            sqlStuff.ForEach(x => x.SqlParameterAssignment(dto, x.SqlParameter));
                            cmd.ExecuteNonQuery();
                        });
            }

            Console.WriteLine("Done in: " + sw.Elapsed);
        }
    }
    public class Data
    {
        public string Title { get; set; }
        public int ID { get; set; }
        public double Foo { get; set; }
    }
}

我认为使用NHibernateEntity Framework这样的标准ORM通常会受益。两者都可以做(可定制的)从类到关系数据库的映射,NHibernate在所有标准DBMS系统之间提供了充分的灵活性。

话虽如此,您应该能够通过使用Linq表达式获得一些功能,这些功能可以稍后编译;这会给你带来更好的表现。

有人告诉过你,反射确实对性能很重要,但你并没有真正通过分析器运行你的代码。

我尝试了你的代码,它花了18毫秒(65000个滴答)来运行,我必须说,与将数据保存在数据库中的时间相比,这是相当快的。但是你说得对,时间确实太多了。我发现你的代码在调用tc时引发了一个异常。转换Byte[]时的ConvertFrom。从clparent中删除字节[]pImage,运行时间下降到850 ticks。

这里的性能问题是异常,而不是反射。

我已经采取自由改变你的GetDBType为:

    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
        {
            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;
                default:
                    try
                    {
                        param.DbType = (DbType)tc.ConvertFrom(type.Name);
                    }
                    catch
                    {
                        // Some error handling
                    }
                    break;
            }
        }
        return param.SqlDbType;
    }

不是替代方法,但只是一个建议:如果类型在运行时重复存储,您可以尝试通过引入一些缓存来调整反射方法。

代替:

PropertyInfo[] props = (t.GetType()).GetProperties();

尝试以下缓存方法:

PropertyInfo[] props = GetProperties(type);

其中GetProperties(Type)是这样实现的:

private Dictionary<Type, PropertyInfo[]> propertyCache;
// ...
public PropertyInfo[] GetProperties(Type t)
{
    if (propertyCache.ContainsKey(t))
    {
        return propertyCache[t];
    }
    else
    {
        var propertyInfos = t.GetProperties();
        propertyCache[t] = propertyInfos;
        return propertyInfos;
    }
}

这就是如何缓存Type.GetProperties()方法调用。您可以对代码的其他部分应用与此类查找相同的方法。例如,您使用param.DbType = (DbType)tc.ConvertFrom(type.Name);的地方。也可以用查找来替换if和switch。但是在你做这样的事情之前你应该做一些分析。如果没有充分的理由,你不应该这样做。

除非使用构建后处理来重写代码,否则没有其他方法可以替代反射。如果您仅使用反射来准备动态发出的类型/方法/委托,并将其自然地包含为策略模式,则可以使用反射而不会出现任何性能问题。

相关文章:
  • 没有找到相关文章