c# – 为什么将存储在对象中的枚举转换为int返回一个字符串?
发布时间:2020-12-16 00:17:34 所属栏目:百科 来源:网络整理
导读:我有一个object类型的属性,它包含一个Enum值,当我使用(int)值转换它时,它返回一个Enum名称的字符串.为什么? 我注意到的代码是在this answer.使用Convert.ToInt32()正确地将Enum强制转换为int,但我只是好奇为什么在使用(int)时我会得到一个字符串.它甚至没有
我有一个object类型的属性,它包含一个Enum值,当我使用(int)值转换它时,它返回一个Enum名称的字符串.为什么?
我注意到的代码是在this answer.使用Convert.ToInt32()正确地将Enum强制转换为int,但我只是好奇为什么在使用(int)时我会得到一个字符串.它甚至没有给我一个错误. 编辑 这是一个快速的样本.我评论了断点的位置,并使用立即窗口来确定输出是什么. MainWindow.xaml.cs public partial class MainWindow : Window { public Int32 SomeNumber { get; set; } public MainWindow() { InitializeComponent(); SomeNumber = 1; RootWindow.DataContext = this; } } public enum MyEnum { Value1 = 1,Value2 = 2,Value3 = 3 } /// <summary> /// Returns true if the int value equals the Enum parameter,otherwise returns false /// </summary> public class IsIntEqualEnumParameterConverter : IValueConverter { #region IValueConverter Members public object Convert(object value,Type targetType,object parameter,CultureInfo culture) { if (parameter == null || value == null) return false; if (parameter.GetType().IsEnum && value is int) { // Breakpoint here return (int)parameter == (int)value; } return false; } public object ConvertBack(object value,CultureInfo culture) { throw new NotImplementedException(); } #endregion } MainWindow.xaml <Window x:Class="WpfApplication5.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfApplication5" Title="MainWindow" Height="350" Width="525" x:Name="RootWindow"> <Window.Resources> <local:IsIntEqualEnumParameterConverter x:Key="IsIntEqualEnumParameterConverter" /> </Window.Resources> <StackPanel> <TextBlock Text="{Binding SomeNumber,Converter={StaticResource IsIntEqualEnumParameterConverter},ConverterParameter={x:Static local:MyEnum.Value1}}" /> </StackPanel> </Window> 编辑#2 只是希望能够澄清一些困惑…… 我说它返回一个字符串,因为在立即窗口中运行?((int)参数)返回枚举名称,而运行?System.Convert.ToInt32(参数)正确显示int. 后来我发现它实际上一直在正确评估DataTrigger.我认为这不是因为我的控件在运行时不可见,但是我发现这是因为我的XAML中的错误(我忘记了一个Grid.Column属性,所以一个控件与另一个控件重叠). 抱歉这个令人困惑的问题. 编辑#3 这里是一些控制台应用程序代码,演示了Jon的情况:) class Program { static void Main(string[] args) { object value; value = Test.Value1; // Put breakpoint here // Run ?(int)value vs Convert.ToInt32(value) in the immediate window // Why does the first return Value1 while the 2nd returns 1? Console.ReadLine(); } } public enum Test { Value1 = 1 } 解决方法
这听起来像是被立即窗口欺骗了.目前尚不清楚你在立即窗口中做了什么,但我可以绝对肯定地说,如果你转换为int,你就不会得到一个字符串.类型系统完全阻止了这种情况的发生.
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |