利用反射,泛型,扩展方法快速获取表单值到实体类

介绍一种通过扩展方法实现表单值自动映射到Model的方法,利用反射和类型转换减少手动赋值的工作量,适用于.NET平台。
f 看到这个随笔: 利用反射,泛型,静态方法快速获取表单值到Model。
才想到我在项目中也有类似实现。。
只不过我用的是扩展方法。最出的出发点就是太烦琐,一直为表单值付值,,
ContractedBlock.gif ExpandedBlockStart.gif Code
using System;
using System.Collections.Generic;
using System.Web;
using System.Reflection;
using System.Xml.Serialization;
using System.IO;
using System.Xml;
using DotNetNuke.Common.Utilities;

namespace UCP.Library
ExpandedBlockStart.gifContractedBlock.gif
{
    
public static class MehtodExtensionsUtility
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{
        
private static bool IsNumeric(object Expression)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
bool isNum;
            
double retNum;
            isNum 
= Double.TryParse(Convert.ToString(Expression), System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out retNum);
            
return isNum;
        }
 
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// 从当前请求中提取类型T,如果不存在,则返回一个new T();
        
/// </summary>
        
/// <typeparam name="T"></typeparam>
        
/// <param name="source"></param>
        
/// <returns></returns>

        public static T SerializableObject<T>(this HttpRequest source) where T:new ()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
object objObject = Activator.CreateInstance(typeof(T));
            PropertyInfo[] ps 
= objObject.GetType().GetProperties();

            PropertyInfo objPropertyInfo 
= null;
            Type objPropertyType 
= null;
            
object objDataValue = null;
            Type objDataType 
= default(Type);
            
for (int i = 0; i < ps.Length; i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
//PropertyInfo item = ps[i];
                
//item.SetValue(obj, string.IsNullOrEmpty(source[item.Name]) ? item.GetValue(obj, null) : source[item.Name], null);



                
//If the Column matches a Property in the Object Map's PropertyInfo Dictionary 
                if (true)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
{
                    objPropertyInfo 
= ps[i];
                    
//Get its type 
                    objPropertyType = objPropertyInfo.PropertyType;

                    
//If property can be set 
                    if (objPropertyInfo.CanWrite)
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
{
                        
//Get the Data Value from the data reader 

                        
if (string.IsNullOrEmpty(source[objPropertyInfo.Name]))
                            
continue;
                        objDataValue 
=HttpUtility.HtmlEncode(source[objPropertyInfo.Name]);
                        
//Get the Data Value's type 
                        objDataType = objDataValue.GetType();

                        
if (objDataValue == System.DBNull.Value)
ExpandedSubBlockStart.gifContractedSubBlock.gif                        
{
                            
// set property value to Null 
                            objPropertyInfo.SetValue(objObject, Null.SetNull(objPropertyInfo), null);
                        }

                        
else if (objPropertyType.Equals(objDataType))
ExpandedSubBlockStart.gifContractedSubBlock.gif                        
{
                            
//Property and data objects are the same type 
                            objPropertyInfo.SetValue(objObject, objDataValue, null);
                        }

                        
else
ExpandedSubBlockStart.gifContractedSubBlock.gif                        
{
                            
// business object info class member data type does not match datareader member data type 
                            try
ExpandedSubBlockStart.gifContractedSubBlock.gif                            
{
                                
//need to handle enumeration conversions differently than other base types 
                                if (objPropertyType.BaseType.Equals(typeof(System.Enum)))
ExpandedSubBlockStart.gifContractedSubBlock.gif                                
{
                                    
// check if value is numeric and if not convert to integer ( supports databases like Oracle ) 
                                    if (IsNumeric(objDataValue))
ExpandedSubBlockStart.gifContractedSubBlock.gif                                    
{
                                        objPropertyInfo.SetValue(objObject, System.Enum.ToObject(objPropertyType, Convert.ToInt32(objDataValue)), 
null);
                                    }

                                    
else
ExpandedSubBlockStart.gifContractedSubBlock.gif                                    
{
                                        objPropertyInfo.SetValue(objObject, System.Enum.ToObject(objPropertyType, objDataValue), 
null);
                                    }

                                }

                                
else if (objPropertyType.FullName.Equals("System.Guid"))
ExpandedSubBlockStart.gifContractedSubBlock.gif                                
{
                                    
// guid is not a datatype common across all databases ( ie. Oracle ) 
                                    objPropertyInfo.SetValue(objObject, Convert.ChangeType(new Guid(objDataValue.ToString()), objPropertyType), null);
                                }

                                
else if (objPropertyType.FullName.Equals("System.Version"))
ExpandedSubBlockStart.gifContractedSubBlock.gif                                
{
                                    objPropertyInfo.SetValue(objObject, 
new Version(objDataValue.ToString()), null);
                                }

                                
else
ExpandedSubBlockStart.gifContractedSubBlock.gif                                
{
                                    
// try explicit conversion 
                                    objPropertyInfo.SetValue(objObject, objDataValue, null);
                                }

                            }

                            
catch
ExpandedSubBlockStart.gifContractedSubBlock.gif                            
{
                                objPropertyInfo.SetValue(objObject, Convert.ChangeType(objDataValue, objPropertyType), 
null);
                            }

                        }

                    }

                }

            }

            
return (T)objObject;
        }

ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// 将当前请求中类型T序列化为XML格式,如果不存在则返回空
        
/// </summary>
        
/// <typeparam name="T"></typeparam>
        
/// <param name="source"></param>
        
/// <returns></returns>

        public static string SerializableToXml<T>(this HttpRequest source) where T : new()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            T obj 
= SerializableObject<T>(source);

            
return obj.SerializableToXml();

            
//System.Text.Encoding encoding = System.Text.ASCIIEncoding.UTF8;
            
//XmlSerializer XMLSerializer = new XmlSerializer(obj.GetType());
            
//using (MemoryStream memoryStream = new MemoryStream())
            
//{
            
//    XmlTextWriter XMLWriter = new XmlTextWriter(memoryStream, encoding);
            
//    XMLSerializer.Serialize(XMLWriter, obj);
            
//    string result = encoding.GetString(memoryStream.ToArray()).Trim();
            
//    XMLWriter.Close();
            
//    memoryStream.Close();
            
//    return result;
            
//}
            
//return "";
        }


ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// 将可系列化的对象序列化为XML格式字符串返回
        
/// 注意:
        
/// 如果字段的类型不是string类型,那么在转换为XML时.会自动使用此类型的默认值做为xml节点的的值.
        
/// 如
        
/// int类型使用0,
        
/// datetime使用0001-01-01
        
/// </summary>
        
/// <param name="obj"></param>
        
/// <returns></returns>

        public static string SerializableToXml(this Object obj)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
string result = "";
            System.Text.Encoding encoding 
= System.Text.ASCIIEncoding.GetEncoding("GB2312");
            XmlSerializer XMLSerializer 
= new XmlSerializer(obj.GetType());
            
using (MemoryStream memoryStream = new MemoryStream())
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                XmlTextWriter XMLWriter 
= new XmlTextWriter(memoryStream, encoding);
                XMLSerializer.Serialize(XMLWriter, obj);
                result 
= encoding.GetString(memoryStream.ToArray()).Trim();
                XMLWriter.Close();
                memoryStream.Close();
            }


            
return result.Replace("encoding=\"gb2312\"""");
        }

ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// 检测当前请求来源是否来自本服务器
        
/// </summary>
        
/// <param name="request"></param>
        
/// <returns></returns>

        public static bool CheckRequstOrigin(this HttpRequest request) 
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{           
            
string userIp = request.UserHostAddress;
           
            
if (userIp == "127.0.0.1" || userIp == "localhost" || userIp == "::1")
                
return true;
            
string strhostname= System.Net.Dns.GetHostName();
            System.Net.IPHostEntry ip
=System.Net.Dns.GetHostByName(strhostname);
            
foreach (System.Net.IPAddress ipA in ip.AddressList)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
if (userIp == ipA.ToString().ToLower().Trim())
                    
return true;
               
            }

            
return false;
        }

    }

}

转载于:https://www.cnblogs.com/solucky/archive/2009/09/02/1558936.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值