Ere*_*rez 1 wpf performance converter
我正在使用 WPF 转换器并想知道在以下示例中使用类成员或局部变量在性能方面哪个更好?
public object Convert(object value, Type targetType, object parameter,System.Globalization.CultureInfo culture)
{
if ((int)value == 1)
return (Color)ColorConverter.ConvertFromString("#FCD44E");
return (Color)ColorConverter.ConvertFromString("#FCD44E");
}
Run Code Online (Sandbox Code Playgroud)
或者 :
Color _color1 = (Color)ColorConverter.ConvertFromString("#FCD44E");
Color _color2 = (Color)ColorConverter.ConvertFromString("#FCD666");
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if ((int)value == 1)
return _color1;
return _color2;
}
Run Code Online (Sandbox Code Playgroud)
性能最好的将使用private static readonly
如下
private static readonly Color Color1 = (Color)ColorConverter.ConvertFromString("#FCD44E");
private static readonly Color Color2 = (Color)ColorConverter.ConvertFromString("#FCD666");
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if ((int)value == 1)
return Color1;
return Color2;
}
Run Code Online (Sandbox Code Playgroud)
请参阅此答案以进行良好的讨论:方法可以静态化,但应该这样做吗?
虽然在性能方面唯一相关的事情是不要在每次调用 - 方法时进行转换Convert
(如其他答案中明确显示的那样),但我永远不会首先编写这样的硬编码转换器,如果您可以参数化某些东西,请毫不犹豫地这样做,例如:
public class OnValueToColorConverter : IValueConverter
{
public int Value { get; set; }
public Color OnValueColor { get; set; }
public Color OffValueColor { get; set; }
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return (int)value == Value ? OnValueColor : OffValueColor;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
}
Run Code Online (Sandbox Code Playgroud)
<vc:OnValueToColorConverter Value="1"
OnValueColor="#FCD44E"
OffValueColor="#FCD666" />
Run Code Online (Sandbox Code Playgroud)
(对于这类事情,通常不会使用转换器,而是使用Style
带有默认设置器的转换器和DataTrigger
用于应更改的值的转换器。)