TryParse 容易被忽略的问题

TryParse方法详解
本文探讨了TryParse方法在处理输入转换时的行为特点,指出即使设置了默认值,转换失败时变量也不会保持原值,而是变为该类型的默认值。

相信对于TryParse 这个方法大家都比较熟悉了,在开发中经常会用作判断输入是否能够正常被转换成需要的类型并赋值。但是本人一直以为在命名变量时设置了一个默认值后,对输入进行TryParse操作,如果失败那么变量值不会改变。不知道有没有同行也有这样的想法,如果有的话就需要注意了,并非如此。

int num=1;

string str="aaa";

int.TryParse(str,out num)

Response.Write(num);

输出结果为:0

同理DateTime.TryParse也是类似,当操作失败时并不是变量的原始值,而是该变量所属类型的默认值。

new public String Text { get { return base.Text; } set { base.Text = LeaveOnlyNumbers(value); } }这里有问题吗?这个Value取得哪的值?using GummingBusiness; using GummingControl; using GummingEntity; using System; using System.Globalization; using System.Linq; using System.Threading; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Input; using System.Windows.Media; namespace Gumming { public class FloatBox : TextBox { #region MaxValue public static readonly DependencyProperty MaxValueProperty = DependencyProperty.Register("MaxValue", typeof(Decimal), typeof(FloatBox), new PropertyMetadata(1000000m, OnMaxValueChanged, CoerceMaxValue)); public Decimal MaxValue { get { return (Decimal)GetValue(MaxValueProperty); } set { SetValue(MaxValueProperty, value); } } private static void OnMaxValueChanged(DependencyObject element, DependencyPropertyChangedEventArgs e) { var control = (FloatBox)element; var maxValue = (Decimal)e.NewValue; } private static object CoerceMaxValue(DependencyObject element, Object baseValue) { var maxValue = (Decimal)baseValue; if (maxValue == Decimal.MaxValue) { return DependencyProperty.UnsetValue; } return maxValue; } #endregion #region MinValue public static readonly DependencyProperty MinValueProperty = DependencyProperty.Register("MinValue", typeof(Decimal), typeof(FloatBox), new PropertyMetadata(-10000m, OnMinValueChanged, CoerceMinValue)); public Decimal MinValue { get { return (Decimal)GetValue(MinValueProperty); } set { SetValue(MinValueProperty, value); } } private static void OnMinValueChanged(DependencyObject element, DependencyPropertyChangedEventArgs e) { var control = (FloatBox)element; var minValue = (Decimal)e.NewValue; // 在这里添加任何当MinValue改变时需要执行的逻辑 // 例如,验证当前值是否在新的最小值和最大值之间 } private static object CoerceMinValue(DependencyObject element, Object baseValue) { var minValue = (Decimal)baseValue; // 你可以在这里添加任何逻辑来强制minValue的值 // 例如,确保minValue不大于MaxValue var maxValue = (Decimal)element.GetValue(MaxValueProperty); if (minValue > maxValue) { return maxValue; // 或者你可以返回一个默认值,比如0m } // 设置全局最小限制 const decimal globalMin = -10000m; // 检查是否设置了不合理的值(比如负数,如果业务逻辑不允许的话) if (minValue < globalMin) // 假设业务逻辑不允许负的最小值 { return globalMin; // 返回0或者一个合理的默认值 } return minValue; } #endregion #region DecimalPlaces 保留小数位数 public static readonly DependencyProperty DecimalPlacesProperty = DependencyProperty.Register( "DecimalPlaces", typeof(int?), typeof(FloatBox), new FrameworkPropertyMetadata(null)); public int? DecimalPlaces { get { return (int?)GetValue(DecimalPlacesProperty); } set { SetValue(DecimalPlacesProperty, value); } } //格式化小数文本 private void UpdateFormattedText() { if (string.IsNullOrWhiteSpace(Text)) return; if (DecimalPlaces == null) return; if (decimal.TryParse(Text, NumberStyles.Float, CultureInfo.CurrentCulture, out decimal value)) { // 按 DecimalPlaces 指定位数格式化 string formatted = value.ToString("F" + DecimalPlaces.Value, CultureInfo.CurrentCulture); // 防止无限递归更新 if (Text != formatted) { Text = formatted; SelectionStart = Text.Length; // 光标移到末尾 SelectionLength = 0; } } } #endregion #region 结构体s /* * The default constructor */ public FloatBox() { TextChanged += new TextChangedEventHandler(OnTextChanged); this.HorizontalContentAlignment = HorizontalAlignment.Center; this.VerticalContentAlignment = VerticalAlignment.Center; //KeyDown += new KeyEventHandler(OnKeyDown); //LostFocus += new RoutedEventHandler(OnLostFocus); this.LostFocus += OnLostFocus; } #endregion #region Properties new public String Text { get { return base.Text; } set { base.Text = LeaveOnlyNumbers(value); } } #endregion #region Functions private bool IsNumberKey(Key inKey) { if (inKey == System.Windows.Input.Key.OemPeriod) { return true; } if (inKey == System.Windows.Input.Key.Decimal) { return true; } if ((inKey < Key.D0 || inKey > Key.D9) && inKey != Key.OemMinus) { if (inKey < Key.NumPad0 || inKey > Key.NumPad9) { return false; } } return true; } private bool IsDelOrBackspaceOrTabKey(Key inKey) { return inKey == Key.Delete || inKey == Key.Back || inKey == Key.Tab; } private string LeaveOnlyNumbers(String inString) { String tmp = inString; foreach (char c in inString.ToCharArray()) { if (!System.Text.RegularExpressions.Regex.IsMatch(c.ToString(), @"^\+?(:?(:?\d+\.\d+)|(:?\d+))|(-?\d+)(\.\d+)?$") && c != '.' && c != '-') { tmp = tmp.Replace(c.ToString(), ""); } } if (tmp.Count(x => x == '.') > 1) { int firstdot = tmp.IndexOf('.'); string header = tmp.Substring(0, firstdot + 1); string strEnd = tmp.Substring(firstdot + 1); tmp = header + strEnd.Replace(".", ""); } return tmp; } #endregion #region Event Functions private void OnLostFocus(object sender, RoutedEventArgs e) { //失去焦点才纠正最大最小值 if (string.IsNullOrWhiteSpace(Text)) { Text = MinValue.ToString(); } else if (decimal.TryParse(Text, NumberStyles.Integer, CultureInfo.CurrentCulture, out decimal value)) { if (value < MinValue) { Text = MinValue.ToString(); // 此时才纠正为 20 } else if (value > MaxValue) { Text = MaxValue.ToString(); } } else { Text = MinValue.ToString(); } GetBindingExpression(TextProperty)?.UpdateSource(); // UpdateFormattedText(); } protected void OnKeyDown(object sender, KeyEventArgs e) { e.Handled = !IsNumberKey(e.Key) && !IsDelOrBackspaceOrTabKey(e.Key); } protected void OnTextChanged(object sender, TextChangedEventArgs e) { if (!System.Text.RegularExpressions.Regex.IsMatch(Text, @"^\+?(:?(:?\d+\.\d+)|(:?\d+))|(-?\d+)(\.\d+)?$")) { base.Text = LeaveOnlyNumbers(Text); } //decimal value = 0; //decimal.TryParse(Text, out value); //if (value > MaxValue) //{ // base.Text = MaxValue.ToString(); //} //if (value < MinValue) //{ // base.Text = MinValue.ToString(); //} this.Select(this.Text.Length, 0); //如果是配方编辑,保存日志 if (Global.ISEditStatus) { if (Global.ISRecipeIterface) { if (this.IsKeyboardFocusWithin) { string buttonText = this.Text?.ToString(); if (!buttonText.EndsWith(".") && buttonText.Contains(".")) SaveOperationLog(buttonText); } /* SolidColorBrush brush = this.Background as SolidColorBrush; if (brush != null) { if (brush.Color == Colors.Red) { } }*/ } } } private void SaveOperationLog(string buttonText) { if (string.IsNullOrEmpty(buttonText)) { return; } SysOperationEntity soe = new SysOperationEntity(); soe.OperationName = Global.CurrentUser.UserName; soe.LogDetail = "[" + Global.FirstLevelPosition + "]" + "[" + Global.TwoLevelPosition + "]" + "[" + Global.ThreeLevelPosition + "]" + "修改[" + Global.EditRecipeName + "]文本内容:" + buttonText; soe.StartTime = DateTime.Now; soe.CreateBy = Global.CurrentUser.UserName; SysOperationDA.Save(soe); Global.UpdateLastActivityTime(); } #endregion } }
最新发布
10-12
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值