csharp: Setting the value of properties reflection
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.IO;
namespace WinPropertyInfo
{
/// <summary>
/// Geovin Du
/// </summary>
public partial class Form1 : Form
{
/// <summary>
///
/// </summary>
/// <returns></returns>
DataTable setData()
{
Image img = Image.FromFile(@"C:\Documents and Settings\geovindu\My Documents\My Pictures\sqlanywhereODBC20180208160133.png");
DataTable dt = new DataTable();
dt.Columns.Add("MyName", typeof(string));
dt.Columns.Add("IsJob", typeof(bool));
dt.Columns.Add("Salary", typeof(float));
dt.Columns.Add("Bonus", typeof(double));
dt.Columns.Add("Insurance", typeof(decimal));
dt.Columns.Add("Age", typeof(int));
dt.Columns.Add("Photo", typeof(Image));
dt.Columns.Add("Birthaday", typeof(DateTime));
//dt.Columns.Add("", typeof(bool));
dt.Rows.Add("geovindu", true, -950, 1789.03, 78.09, 79, img, DateTime.Now);
dt.Rows.Add("塗聚文", true, -8950, 789.03, 5178.09, 29, img, DateTime.Now);
return dt;
}
/// <summary>
///
/// </summary>
public Form1()
{
InitializeComponent();
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form1_Load(object sender, EventArgs e)
{
List<GeovinDuInfo> list = new List<GeovinDuInfo>();
Image img = Image.FromFile(@"C:\Documents and Settings\geovindu\My Documents\My Pictures\sqlanywhereODBC20180208160133.png",false);
byte[] imgbyt = ToByteArray(img);
try
{
//GeovinDuInfo info = new GeovinDuInfo();
//SetPropertyValue(info, "MyName", "geovindu");
//SetPropertyValue(info, "IsJob", true);
//SetPropertyValue(info, "Salary", -850);
//SetPropertyValue(info, "Bonus", 78.02);
//SetPropertyValue(info, "Insurance", 78.02);
//SetPropertyValue(info, "Age", 78);
//SetPropertyValue(info, "Photo", imgbyt); //不可賦值
//SetPropertyValue(info, "Birthaday", DateTime.Now);
//list.Add(info);
DataTable dt = setData();
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
GeovinDuInfo info = DataRowToModel(dt.Rows[i]);
list.Add(info);
}
}
this.dataGridView1.DataSource = list;//setData();//
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
/// <summary>
/// 賦值
/// </summary>
/// <param name="obj"></param>
/// <param name="propertyName"></param>
/// <param name="propertyValue"></param>
public static void SetPropertyValue(object obj, string propertyName, object propertyValue)
{
if (obj == null || string.IsNullOrEmpty(propertyName)) //IsNullOrWhiteSpace
{
return;
}
Type objectType = obj.GetType();
PropertyInfo propertyDetail = objectType.GetProperty(propertyName);
if (propertyDetail != null && propertyDetail.CanWrite)
{
Type propertyType = propertyDetail.PropertyType;
Type dataType = propertyType;
// Check for nullable types
if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
// Check for null or empty string value.
if (propertyValue == null || string.IsNullOrEmpty(propertyValue.ToString()))
{
propertyDetail.SetValue(obj, null,null);
return;
}
else
{
dataType = propertyType.GetGenericArguments()[0];
}
}
propertyValue = Convert.ChangeType(propertyValue, propertyType);
propertyDetail.SetValue(obj, propertyValue,null);
}
}
/// <summary>
///
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public bool ValidateData(object data)
{
foreach (PropertyInfo propertyInfo in data.GetType().GetProperties())
{
if (propertyInfo.PropertyType == typeof(string))
{
string value = propertyInfo.GetValue(data, null);
if (value == "geovindu")
{
return false;
}
}
}
return true;
}
/// <summary>
///
/// </summary>
/// <param name="row"></param>
/// <returns></returns>
public GeovinDuInfo DataRowToModel(DataRow row)
{
GeovinDuInfo model = new GeovinDuInfo();
if (row != null)
{
//利用反射获得属性的所有公共属性
Type modelType = model.GetType();
for (int i = 0; i < row.Table.Columns.Count; i++)
{
//查找实体是否存在列表相同的公共属性
PropertyInfo proInfo = modelType.GetProperty(row.Table.Columns[i].ColumnName);
Type propertyType = proInfo.PropertyType;
Type dataType = propertyType;
if (proInfo != null && row[i] != DBNull.Value)
{
if (proInfo != null && proInfo.CanWrite)
{
}
if (dataType.Equals(typeof(Single))) //要考慮數据類型,否則會出錯
{
//propertyValue = Convert.ToSingle(propertyValue);
proInfo.SetValue(model, Convert.ToSingle(row[i], null)); //float類型轉換
}
else if (dataType.Equals(typeof(Double)))
{
proInfo.SetValue(model, Convert.ToDouble(row[i], null));
}
else if (dataType.Equals(typeof(Boolean)))
{
proInfo.SetValue(model, Convert.ToBoolean(row[i], null));
}
else if (dataType.Equals(typeof(Int32)))
{
proInfo.SetValue(model,Convert.ToInt32(row[i],null));
}
else if (dataType.Equals(typeof(Decimal)))
{
proInfo.SetValue(model, Convert.ToDecimal(row[i], null));
}
else
{
//proInfo.SetValue(model, Convert.ChangeType(row[i], propertyType), null);
proInfo.SetValue(model, row[i], null);//用索引值设置属性值 負數 float
}
}
}
}
return model;
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
}
/// <summary>
///
/// </summary>
/// <param name="imageIn"></param>
/// <returns></returns>
public static byte[] ToByteArray(Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
return ms.ToArray();
}
//Convert byte[] array to Image:
/// <summary>
///
/// </summary>
/// <param name="byteArrayIn"></param>
/// <returns></returns>
public static Image ToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
}
/// <summary>
/// 塗聚文 涂聚文
/// Geovin Du
///
/// </summary>
public class GeovinDuInfo
{
private string _MyName = string.Empty;
/// <summary>
///
/// </summary>
public string MyName
{
get { return _MyName; }
set { _MyName = value; }
}
private bool _IsJob = true;
/// <summary>
///
/// </summary>
public bool IsJob
{
get { return _IsJob; }
set { _IsJob = value; }
}
private float _Salary = 0;
/// <summary>
///
/// </summary>
public float Salary
{
get { return _Salary; }
set { _Salary = value; }
}
private double _Bonus = 0.00;
/// <summary>
///
/// </summary>
public double Bonus
{
get { return _Bonus; }
set { _Bonus = value; }
}
private decimal _Insurance;
/// <summary>
///
/// </summary>
public decimal Insurance
{
get { return _Insurance; }
set { _Insurance = value; }
}
private int _Age = 0;
/// <summary>
///
/// </summary>
public int Age
{
get { return _Age; }
set { _Age = value; }
}
private Image _Photo;
/// <summary>
///
/// </summary>
public Image Photo
{
get { return _Photo; }
set { _Photo = value; }
}
private DateTime _Birthaday = DateTime.Now;
/// <summary>
///
/// </summary>
public DateTime Birthaday
{
get { return _Birthaday; }
set { _Birthaday = value; }
}
}
}
哲学管理(学)人生, 文学艺术生活, 自动(计算机学)物理(学)工作, 生物(学)化学逆境, 历史(学)测绘(学)时间, 经济(学)数学金钱(理财), 心理(学)医学情绪, 诗词美容情感, 美学建筑(学)家园, 解构建构(分析)整合学习, 智商情商(IQ、EQ)运筹(学)生存.---Geovin Du(涂聚文)
浙公网安备 33010602011771号