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

  

csharp: Setting the value of properties reflection的更多相关文章

  1. 无法识别的配置节点 applicationSettings/* Properties.Settings 解决方法

    http://blog.csdn.net/yaoxtao/article/details/7766888 在项目中引用web service时,偶然出现 无法识别的配置节点 applicationSe ...

  2. Learning WCF Chapter2 Data Contracts

    A data contract describes how CLR types map to XSD schema definitions. Data contracts are the prefer ...

  3. 关于C#你应该知道的2000件事

    原文 关于C#你应该知道的2000件事 下面列出了迄今为止你应该了解的关于C#博客的2000件事的所有帖子. 帖子总数= 1,219 大会 #11 -检查IL使用程序Ildasm.exe d #179 ...

  4. mybatis源码配置文件解析之二:解析settings标签

    在前边的博客中分析了mybatis解析properties标签,<mybatis源码配置文件解析之一:解析properties标签>.下面来看解析settings标签的过程. 一.概述 在 ...

  5. Android Studio 入门

    本文适用于从Eclipse转AndroidStudio的开发者 最近打算写一个系列的android初级开发教程,预计40篇以上的文章,结合我实际工作中的经验,写一些工作中经常用到的技术,让初学者可以少 ...

  6. Windows Service--Write a Better Windows Service

    原文地址: http://visualstudiomagazine.com/Articles/2005/10/01/Write-a-Better-Windows-Service.aspx?Page=1 ...

  7. Creating a SharePoint Sequential Workflow

    https://msdn.microsoft.com/en-us/library/office/hh824675(v=office.14).aspx Creating a SharePoint Seq ...

  8. zookeeper学习系列:四、Paxos算法和zookeeper的关系

    一.问题起源 淘宝搜索的博客 http://www.searchtb.com/2011/01/zookeeper-research.html  提到Paxos是zookeeper的灵魂 有一篇文章标题 ...

  9. SQL Server Analysis Services SSAS Processing Error Configurations

    转载:https://www.mssqltips.com/sqlservertip/3476/sql-server-analysis-services-ssas-processing-error-co ...

随机推荐

  1. Linux学习---GCC编译常见错误

    预处理错误: No such file or directory 出错原因:①包含错误:eg  #include <abc.h> //abc.h为用户自行编写文件 解决方法:⑴应改为#in ...

  2. MBR内容解析

    原先博客放弃使用,几篇文章搬运过来 MBR(Master Boot Record)即主引导记录. 使用Winhex打开,磁盘的第一扇区: 黄色部分(000H-1B7H):引导分区 作用:在主板BIOS ...

  3. gitlab 搭建自己的源代码管理器

    首先  gitlab 是不支持 windows.mac os 的,具体支持的系统参照官网的 1.安装虚拟机 ubuntu16.04 需要注意的一点:gitlab 服务器 与 客户端必须在一个局域网内( ...

  4. js-function复制变量值和传递参数

    <title>function复制变量值</title></head><body> <script> var a={ num:10 } // ...

  5. Vuejs——(9)组件——props数据传递

    版权声明:出处http://blog.csdn.net/qq20004604   目录(?)[+]   本篇资料来于官方文档: http://cn.vuejs.org/guide/components ...

  6. day15_雷神_前端03

    # 前端 day03 内容回顾 javascript: 1.ECMAScript5.0 es6(阮一峰) es7 es8 (1)声明变量 var let (2)内置函数 Date Math.rando ...

  7. git & github 同步文件

    step1 : 在github上建立一个 repository https://github.com/ntu-juking/softwaretesting.git repository name is ...

  8. Varnish实现Web站点加速

    Varnish 是一款高性能的开源HTTP加速器,挪威最大的在线报纸 Verdens Gang使用3台Varnish代替了原来的12台Squid,性能比以前更好. Varnish 的作者Poul-He ...

  9. JavaScript使用浏览器内置XML解析器解析DOM对象

    所有现代浏览器都内建了供读取和操作 XML 的 XML 解析器.解析器把 XML 转换为 XML DOM 对象 (可通过 JavaScript 操作的对象). 一.获取DOM对象 XMLHttpReq ...

  10. kubernetes集群搭建(7):常见问题及处理

    尤其在创建pod的时候,会遇见各类问题,请通过下列命令来查看错误详情 kubectl describe pod xxxxxx 1.问题现象:镜像始终获取不下来 解决办法:为docker设置镜像源 [r ...