只需要使用Convert.ChangeType即可
var eval = new DataTable(); var objType = order.GetType(); var propertyVal = objType.GetProperty(propertyName[1]); if (propertyVal != null) { var val = propertyVal.GetValue(order, null).ToString(); //TODO: 神奇的方法 var result = eval.Compute( $"{val} {action["Expression"].Value<string>()} {action["Value"].Value<string>()}", ""); propertyVal.SetValue(order, Convert.ChangeType(result, propertyVal.PropertyType), null); }
想知道ChangeType是怎么实现的?其实就是封装了一堆判断hhhh
public static object ChangeType(object value, TypeCode typeCode, IFormatProvider provider) { if (value == null && (typeCode == TypeCode.Empty || typeCode == TypeCode.String || typeCode == TypeCode.Object)) { return null; } IConvertible convertible = value as IConvertible; if (convertible == null) { throw new InvalidCastException(Environment.GetResourceString("InvalidCast_IConvertible")); } switch (typeCode) { case TypeCode.Empty: { throw new InvalidCastException(Environment.GetResourceString("InvalidCast_Empty")); } case TypeCode.Object: { return value; } case TypeCode.DBNull: { throw new InvalidCastException(Environment.GetResourceString("InvalidCast_DBNull")); } case TypeCode.Boolean: { return convertible.ToBoolean(provider); } case TypeCode.Char: { return convertible.ToChar(provider); } case TypeCode.SByte: { return convertible.ToSByte(provider); } case TypeCode.Byte: { return convertible.ToByte(provider); } case TypeCode.Int16: { return convertible.ToInt16(provider); } case TypeCode.UInt16: { return convertible.ToUInt16(provider); } case TypeCode.Int32: { return convertible.ToInt32(provider); } case TypeCode.UInt32: { return convertible.ToUInt32(provider); } case TypeCode.Int64: { return convertible.ToInt64(provider); } case TypeCode.UInt64: { return convertible.ToUInt64(provider); } case TypeCode.Single: { return convertible.ToSingle(provider); } case TypeCode.Double: { return convertible.ToDouble(provider); } case TypeCode.Decimal: { return convertible.ToDecimal(provider); } case TypeCode.DateTime: { return convertible.ToDateTime(provider); } case TypeCode.Object | TypeCode.DateTime: { throw new ArgumentException(Environment.GetResourceString("Arg_UnknownTypeCode")); } case TypeCode.String: { return convertible.ToString(provider); } default: { throw new ArgumentException(Environment.GetResourceString("Arg_UnknownTypeCode")); } } }
又机智的水了一贴….
四月水一贴…
好久不见…
OvO 测试…
(╯‵□′)╯︵┻━┻
贊哦!!!
过来看看、支持一下
代码这些东西,不懂的
技术帝啊。
就看看啊!
代码还是有点弱