核心代码return (T)(object)xxx;
示例代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 |
public static T GetUnitSettingById<T>(int id) where T : Setting { if (typeof(T).Equals(typeof(BodySetting))) { var body = BodySetting_table.Instance.GetEntityByPrimaryKey(id); if (body!=null) { return (T)(object)body; } } return null; } |
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 |
/// <summary> /// 从DataRow里获取指定字段的值 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="row"></param> /// <param name="columnName"></param> /// <returns></returns> private T GetValue<T>(DataRow row, string columnName) { var resultObj = new object(); switch (typeof(T).Name.ToLower()) { case "int32": var numInt = 0; if (row.Table.Columns.Contains(columnName)) int.TryParse(row.Field<string>(columnName), out numInt); resultObj = numInt; break; case "int64": var numLong = 0l; if (row.Table.Columns.Contains(columnName)) long.TryParse(row.Field<string>(columnName), out numLong); resultObj = numLong; break; case "decimal": var numDecimal = 0m; if (row.Table.Columns.Contains(columnName)) decimal.TryParse(row.Field<string>(columnName), out numDecimal); resultObj = numDecimal; break; case "string": resultObj = row.Table.Columns.Contains(columnName) ? row.Field<string>(columnName) : string.Empty; break; case "datetime": var outDatetime = new DateTime(); if (row.Table.Columns.Contains(columnName)) DateTime.TryParse(row.Field<string>(columnName), out outDatetime); resultObj = outDatetime; break; } return (T)resultObj; } |
参考:https://blog.csdn.net/iningwei/article/details/88978598