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 ...
随机推荐
- Spring的介绍与搭建
一.Spring的介绍 二.Spring的搭建 (1)导包 (2)创建一个对象 (3)书写配置注册对象到容器 (4)代码测试
- FastJSON基础
对象的类型 json文本 json数组 json对象 java对象 类型的转换 json文本 转 json对象 JSON.parseObject(str) json文本 ...
- Win7 VS2015 NASM汇编语言环境配置
参考了以下两个博客文章 http://blog.csdn.net/x356982611/article/details/51260841 http://www.cnblogs.com/antonioz ...
- 单台机器安装zookeeper
先给一堆学习文档,方便以后查看 官网文档地址大全: OverView(概述) http://zookeeper.apache.org/doc/r3.4.6/zookeeperOver.html Get ...
- jvm虚拟机--垃圾回收子系统
转载自cyc2018的github:https://github.com/CyC2018/Interview-Notebook/blob/master/notes/Java%20%E8%99%9A%E ...
- 将json对象转化成jsonp对象
这个Demo用来检查是否具有唯一性 //检查 /user/check/{param}/{type} @RequestMapping("/check/{param}/{type}") ...
- C++回调:利用Sink
Sink的本质是利用C++的封装.继承.多态的面向对象来实现,从实现角度来说,更优于函数指针回调: // cbBysink.cpp : Defines the entry point for the ...
- ASP.NET Core OceLot 微服务实践
1.OceLot中间件介绍 在传统的BS应用中,随着业务需求的快速发展变化,需求不断增长,迫切需要一种更加快速高效的软件交付方式.微服务可以弥补单体应用不足,是一种更加快速高效软件架构风格.单体应用被 ...
- Javascript高级编程学习笔记(12)—— 引用类型(1)Object类型
前面的文章中我们知道JS中的值分为两种类型 基础类型的值和引用类型的值 基础类型的值我已经大概介绍了一下,今天开始后面几天我会为大家介绍一下引用类型的值 Object类型 对象是引用类型的值的实例,在 ...
- 第二十九节:Java基础知识-类,多态,Object,数组和字符串
前言 Java基础知识-类,多态,Object,数组和字符串,回顾,继承,类的多态性,多态,向上转型和向下转型,Object,数组,多维数组,字符串,字符串比较. 回顾 类的定义格式: [类的修饰符] ...