我有一个 object
类型的属性,它包含一个 Enum
值,当我使用 (int)value
转换它时,它返回枚举名称的 string
。为什么?
我注意到的代码在 this answer 中.使用 Convert.ToInt32()
可以将 Enum
正确地转换为 int
,但我很好奇为什么在使用 (整数)
。它甚至没有向我抛出错误。
编辑
这是一个快速示例。我在放置断点的位置添加了注释,并使用即时窗口确定输出内容。
主窗口.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, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
主窗口.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)parameter)
返回枚举名称,而运行 ?System.Convert.ToInt32(parameter)
正确显示了 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
,您会< em>不 返回一个string
。类型系统完全阻止了这种情况的发生。
关于c# - 为什么将存储在对象中的枚举转换为 int 会返回一个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7111901/