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; }
} } }
csharp: Setting the value of properties reflection的更多相关文章
- 无法识别的配置节点 applicationSettings/* Properties.Settings 解决方法
http://blog.csdn.net/yaoxtao/article/details/7766888 在项目中引用web service时,偶然出现 无法识别的配置节点 applicationSe ...
- Learning WCF Chapter2 Data Contracts
A data contract describes how CLR types map to XSD schema definitions. Data contracts are the prefer ...
- 关于C#你应该知道的2000件事
原文 关于C#你应该知道的2000件事 下面列出了迄今为止你应该了解的关于C#博客的2000件事的所有帖子. 帖子总数= 1,219 大会 #11 -检查IL使用程序Ildasm.exe d #179 ...
- mybatis源码配置文件解析之二:解析settings标签
在前边的博客中分析了mybatis解析properties标签,<mybatis源码配置文件解析之一:解析properties标签>.下面来看解析settings标签的过程. 一.概述 在 ...
- Android Studio 入门
本文适用于从Eclipse转AndroidStudio的开发者 最近打算写一个系列的android初级开发教程,预计40篇以上的文章,结合我实际工作中的经验,写一些工作中经常用到的技术,让初学者可以少 ...
- Windows Service--Write a Better Windows Service
原文地址: http://visualstudiomagazine.com/Articles/2005/10/01/Write-a-Better-Windows-Service.aspx?Page=1 ...
- Creating a SharePoint Sequential Workflow
https://msdn.microsoft.com/en-us/library/office/hh824675(v=office.14).aspx Creating a SharePoint Seq ...
- zookeeper学习系列:四、Paxos算法和zookeeper的关系
一.问题起源 淘宝搜索的博客 http://www.searchtb.com/2011/01/zookeeper-research.html 提到Paxos是zookeeper的灵魂 有一篇文章标题 ...
- SQL Server Analysis Services SSAS Processing Error Configurations
转载:https://www.mssqltips.com/sqlservertip/3476/sql-server-analysis-services-ssas-processing-error-co ...
随机推荐
- valgrind内存检测工具
valgrind 那点事 ---------------------------------------内存检测工具 valgrind要使用此工具,可以使用--tool=memcheck 在Valgr ...
- linux 下动态链接实现原理
符号重定位 讲动态链接之前,得先说说符号重定位. c/c++ 程序的编译是以文件为单位进行的,因此每个 c/cpp 文件也叫作一个编译单元(translation unit), 源文件先是被编译成一个 ...
- 一道面试题(C语言)
题:输入一个数,列出所有加和等于该数的式子. 分析: 以 6 为例: 从上面的分析就比较容易找到规律了. C语言代码: #include <stdio.h> int main() { in ...
- 从零搭建java后台管理系统(二)mysql和redis安装
接上篇开始安装mysql和redis 注意了,如果用阿里云服务器,外网访问的端口必须在安全组开启,否则外网访问不通 三.服务器安装redis和mysql 本次环境搭建将所有第三方服务会安装在阿里云服务 ...
- javascript History对象属性和方法
History对象 History对象包含用户(在浏览器窗口中)访问过的URL length: 返回浏览器历史列表中的URL数量(打开浏览器,访问淘宝,返回1,再访问百度,返回2) History对象 ...
- Ajax 的学习
(一)基础知识和新的概念 1,AJAX 就是浏览器提供的一套 API,可以通过 JavaScript 调用,从而实现通过代码控制请求与响应.实现 网络编程. 2,AJAX(Asynchr ...
- google的android工具常用下载路径
android的bug工具在网上搜的时候,经常被索引到垃圾网站,今天找到了一个网站下载android工具 都是最新的,十分不错,就做个分享吧. Google 提供了 Windows.macOS 以及 ...
- Angular使用总结 --- 通过指令动态添加组件
之前自己写的公共组件,都是会先引入,需要调起的时候再通过service控制公共组件状态.值.回调函数什么的.但是有一些场景不适合这种方式,还是动态添加组件更加好.通过写过的一个小组件来总结下. 创建组 ...
- python多进程没有锁队列范例
假设有一些任务要完成.为了完成这项任务,将使用几个过程.所以,将保持两个队列.一个包含任务,另一个包含已完成任务的日志. 然后实例化流程来完成任务.请注意,python队列类已经同步. 这意味着,我们 ...
- git reset命令使用
版本回退 当前有三个commit提交版本commit1commit2commit3Git必须知道当前版本是哪个版本,在Git中,用HEAD表示当前版本上一个版本是HEAD^,上上一个版本是HEAD^^ ...