有关转换问题

Convert.ChangeType 的运用

JOBEntity job=new JOBEntity();

Type t = job.GetType();

PropertyInfo[] info = t.GetProperties();

 foreach(PropertyInfo i in info)
{
       //value 必须保证有效性,否则要对 PropertyType 进行 typeof 判断 

       if(i.PropertyType.IsGenericType)//是否为泛形类型
            i.SetValue(job, Convert.ChangeType(value, i.PropertyType.GetGenericArguments()[0]), null);
       else
            i.SetValue(job, Convert.ChangeType(value,i.PropertyType), null);
}

-----------------------------------------------------------------------------

实体转换成XML

[Serializable]
public class SmtpConfig
{

  public string Host{get;set;}

  public int Port{get;set;}

}

SmtpConfig _config=new SmtpConfig{Host="127.0.0.1", Port=21;}

using (StreamWriter sw = new StreamWriter(xmlpath, false, System.Text.Encoding.Default))
{
XmlSerializer xs = new XmlSerializer(typeof(SmtpConfig));
xs.Serialize(sw, _config);
sw.Close();
}

 

-------------------------------------------------

IDataRecord 转换为实体对象

private static void ReaderToEntity(IDataRecord reader, Object entity)  
    {  
        for (int i = 0; i < reader.FieldCount; i++)  
        {  
            System.Reflection.PropertyInfo propertyInfo = entity.GetType().GetProperty(reader.GetName(i));  
            if (propertyInfo != null)  
            {  
                if (reader.GetValue(i) != DBNull.Value)  
                {  
                    propertyInfo.SetValue(entity, reader.GetValue(i), null);  
                }  
            }  
        }  
    }  

 

posted @ 2012-03-07 15:34  Yu  阅读(169)  评论(0编辑  收藏  举报