试图创建使用反射通用型读写器(trying to create generic Type Reade

2019-10-17 22:05发布

的扩展,这个问题通过静态反射信息静态泛型方法

我试着去建立一个通用型读写器,因为我使用类做了很多的数据访问,我想创建一个非常通用的方法,可以让没有太多的代码读取数据。

,做阅读的大部分代码的部分看起来像这样

 public static T Read<T>(string field,IDataRecord data )
    {
        Type type1 = typeof (T);
        try
        {
            if (type1 == typeof( String ))
            {
                return (T)Convert.ChangeType( readString( data[field].ToString() ), typeof( T ) );
            }
            if (type1 == typeof( int? ))
            {
                return (T)Convert.ChangeType( readIntN( data[field].ToString() ), typeof( T ) );
            }
            if (type1 == typeof( Guid? ))
            {
                return (T)Convert.ChangeType( readGuidN( data[field].ToString() ), typeof( T ) );
            }
            if (type1 == typeof( double? ))
            {
                return (T)Convert.ChangeType( readDoubleN( data[field].ToString() ), typeof( T ) );
            }
            if (type1 == typeof( decimal? ))
            {
                var res = readDecimalN(data[field].ToString());
                return (T)Convert.ChangeType( res, typeof( T ) );
            }
            if (type1 == typeof( float? ))
            {
                return (T)Convert.ChangeType( readFloatN( data[field].ToString() ), typeof( T ) );
            }
            if (type1 == typeof( bool? ))
            {
                return (T)Convert.ChangeType( readBoolN( data[field].ToString() ), typeof( T ) );
            }
            if (type1 == typeof( DateTime? ))
            {
                return (T)Convert.ChangeType( readDatetimeN( data[field].ToString() ), typeof( T ) );
            }
            if (type1 == typeof( int ))
            {
                return (T)Convert.ChangeType( readInt( data[field].ToString() ), typeof( T ) );
            }
            if (type1 == typeof( long? ))
            {
                return (T)Convert.ChangeType( readLongN( data[field].ToString() ), typeof( T ) );
            }
            if (type1 == typeof( long ))
            {
                return (T)Convert.ChangeType( readLong( data[field].ToString() ), typeof( T ) );
            }
            if (type1 == typeof( Guid ))
            {
                return (T)Convert.ChangeType(readGuid( data[field].ToString() ), typeof( T ) );
            }
            if (type1 == typeof( double ))
            {
                return (T)Convert.ChangeType( readDouble( data[field].ToString() ), typeof( T ) );
            }
            if (type1 == typeof( decimal ))
            {
                return (T)Convert.ChangeType( readDecimal( data[field].ToString() ), typeof( T ) );
            }
            if (type1 == typeof( float ) || type1 == typeof( Single ))
            {
                return (T)Convert.ChangeType( readFloat( data[field].ToString() ), typeof( T ) );
            }
            if (type1 == typeof( bool ))
            {
                return (T)Convert.ChangeType( readBool( data[field].ToString() ), typeof( T ) );
            }
            if (type1 == typeof( DateTime ))
            {
                return (T)Convert.ChangeType( readDatetime( data[field].ToString() ), typeof( T ) );
            }
        }
        catch (Exception)
        {
            throw;
        }
        throw new Exception(String.Format("Data Type Not Supported: {0}", type1));
    }

然而,这是引发无效转换异常。

该方法的readXXX正在罚款的问题是在每个return语句中存在的

我一直在使用也尝试

public static T SafeConvert<T>(string s, T defaultValue)
{
if ( string.IsNullOrEmpty(s) )
    return defaultValue;
return (T)Convert.ChangeType(s, typeof(T));
} 

但它仍然失败

编辑:

该方法被称为通过

private static List<T> GetItems<T>(IDataReader reader)
    {
        var items = new List<T>();
        while (reader.Read())
        {
            Type type1 = typeof (T);
            var item = (T) Activator.CreateInstance(typeof (T), new object[] {});
            foreach (PropertyInfo info in type1.GetProperties())
            {
                int written = 0;
                if (info.CanWrite)
                {
                    #region

                    try
                    {
                        Type dataType = info.PropertyType;
                        MethodInfo method = typeof (DataReader).GetMethod("Read",BindingFlags.Static | BindingFlags.Public);
                        MethodInfo generic = method.MakeGenericMethod(dataType);
                        var t = generic.Invoke(null, new object[] {info.Name, reader});
                        info.SetValue( item, t );

更多...

人们似乎是问什么我用这个,最终它可以让我在一行中创建一个IEnumerable是从任意源读取无论是通过传递一个文件位置,或者SQL查询即CSV或SQL

//returns Ienumerable<MyClass>
var list = Reader.ReadSql<MyClass>(DataBases.Test,"select * from TestTable where someAttribute  = 1");
// also returns Ienumerable MyClass
var list2 = Readre.ReadCsv<MyClass>(@"c:\file1.csv",","); 

我现在运行,但它要求如果我希望重构是到一个通用的Read方法各实施的dataType == typeof运算(字符串)一长串的repetiiton但我有使用转换的麻烦

Answer 1:

你更新的问题说,它的工作原理,但要重构。 好了,你可以!

Dictionary<Type, Func<string, IDataRecord, object>> converters_ = new Dictionary<Type, Func<string, IDataRecord, object>>();

converters_[typeof(bool)] = (s) => { return readBoolN( data[s].ToString() ); };
// repeat for other types:

Then

 public static T Read<T>(string field,IDataRecord data )
 {
     return (T)converters_[typeof(T)](field, data);
 }


Answer 2:

  1. 您调用GetMethod没有一个Binder ,你怎么能得到泛型的预期吗?

  2. Read<T>不带参数将被调用可以用来推断类型,你希望当你与一个类型参数调用它是每次?

  3. 如果2你所期望的,那么什么是从刚刚调用不同GetXXX方法?

我无法按照原来的设计,但考虑下面的代码:

public static partial class DataReaderExtensions {
    /// <summary>
    /// <para>Copy data to target object</para>
    /// <para>Class which implements IDataRecord usually also implements IDataReader</para>
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="data"></param>
    /// <param name="target"></param>
    /// <returns>the count of field or property copied</returns>
    public static int CopyTo<T>(this IDataRecord data, T target) {
        return (
            from column in
                Enumerable.Range(0, data.FieldCount).Select(
                    (x, i) => new {
                        DataType=data.GetFieldType(i),
                        ColumnName=data.GetName(i)
                    }
                    )
            let type=target.GetType()
            from member in type.GetMembers()
            let typeMember=
                member is PropertyInfo
                    ?(member as PropertyInfo).PropertyType
                    :member is FieldInfo
                        ?(member as FieldInfo).FieldType
                        :default(MemberInfo)
            where typeMember==column.DataType
            let name=member.Name
            where name==column.ColumnName
            let invokeAttr=
                BindingFlags.SetProperty|BindingFlags.SetField|
                BindingFlags.NonPublic|BindingFlags.Public|
                BindingFlags.Instance
            select type.InvokeMember(name, invokeAttr, default(Binder), target, new[] { data[name] })
            ).Count();
    }
}

你会在复制data的语句,像直接给自定义类型的实例:

reader.CopyTo(myObject); 

它会自动映射与字段/属性列名,无论公/非公开; 最后返回复制的元素数量。



文章来源: trying to create generic Type Reader using reflection