我有一个类型的属性object,它包含一个Enum值,当我使用(int)value它时,它返回一个stringEnum的名称.为什么?
我注意到的代码在这个答案中.使用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
}
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
编辑#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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1194 次 |
| 最近记录: |