csharp: Setting the value of properties reflection
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 | 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(涂聚文)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南