有没有更好的方法来编写此代码..
MyObject pymt = new MyObject(); pymt.xcol1id= Convert.IsDBNull(row["col1id"]) ? 0 : (int)row["col1id"]; pymt.xcold2id= Convert.IsDBNull(row["col2id"]) ? String.Empty : (string)row["col2id"]; pymt.xcold3id = Convert.IsDBNull(row["CustNum"]) ? 0 : (decimal)row["xcold3id"];
这可以用一种更干净的方式来完成..就像通用方法一样?
您可以像这样制作通用扩展方法:
public static class DataRowExtensions { public static T GetValueOrDefault(this DataRow row, string key) { return row.GetValueOrDefault(key, default(T)); } public static T GetValueOrDefault (this DataRow row, string key, T defaultValue) { if (row.IsNull(key)) { return defaultValue; } else { return (T)row[key]; } } }
用法:
MyObject pymt = new MyObject(); pymt.xcol1id = row.GetValueOrDefault("col1id"); pymt.xcold2id = row.GetValueOrDefault ("col2id", String.Empty); pymt.xcold3id = row.GetValueOrDefault ("CustNum"]);
如果您使用的是.NET 3.5,并且没有重新发明Microsoft已经为您编写的扩展方法,那么绝对有更简洁的方法来编写该代码.只需添加对System.Data.DataSetExtensions.dll的引用,您就可以执行此操作:
MyObject pymt = new MyObject { xcol1id = row.Field("col1id") ?? 0, xcol2id = row.Field ("col2id") ?? String.Empty, xcol3id = row.Field ("col3id") ?? 0M };
在这种情况下,我倾向于使用空合并运算符.此外,DBNull.ToString返回string.Empty,因此您不必在那里做任何花哨的事情.
MyObject pymt = new MyObject(); pymt.xcol1id= row["col1id"] as int? ?? 0; pymt.xcold2id= row["col2id"].ToString(); pymt.xcold3id = row["CustNum"] as decimal? ?? 0;