【发布时间】:2011-08-18 17:57:23
【问题描述】:
我有一个object 类型的属性,它包含一个Enum 值,当我使用(int)value 对其进行转换时,它返回一个枚举名称的string。为什么?
我注意到这一点的代码在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, Type targetType, object parameter, 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)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
}
【问题讨论】:
-
你是把它变成一个字符串吗?您是否将其投射到 Console.WriteLine() 中?我没有看到同样的问题。将其转换为 int 似乎给了我预期的行为。
-
那是不可能的。你不能直接施法并得到不同类型的东西。
-
@Rachel 那只会以文本形式显示表达式的值;不过,表达式本身不是字符串。
-
请粘贴您在即时窗口中看到的内容的副本。
-
我刚刚尝试了 Rachel 的控制台代码,得到了相同的结果。有趣的是,如果将
value的类型更改为Test,它会显示为1...