Browse Source

Merge pull request #6533 from YohDeadfall/faster-type-utils

Compiler intrinsic based type nullability check
release/0.10.8
Dan Walmsley 5 years ago
committed by Steven Kirk
parent
commit
8726c0b0de
  1. 2
      src/Avalonia.Base/Data/Converters/FuncValueConverter.cs
  2. 14
      src/Avalonia.Base/Utilities/TypeUtilities.cs

2
src/Avalonia.Base/Data/Converters/FuncValueConverter.cs

@ -26,7 +26,7 @@ namespace Avalonia.Data.Converters
/// <inheritdoc/> /// <inheritdoc/>
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{ {
if (value is TIn || (value == null && TypeUtilities.AcceptsNull(typeof(TIn)))) if (TypeUtilities.CanCast<TIn>(value))
{ {
return _convert((TIn)value); return _convert((TIn)value);
} }

14
src/Avalonia.Base/Utilities/TypeUtilities.cs

@ -3,6 +3,7 @@ using System.ComponentModel;
using System.Globalization; using System.Globalization;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
using System.Runtime.CompilerServices;
namespace Avalonia.Utilities namespace Avalonia.Utilities
{ {
@ -93,6 +94,17 @@ namespace Avalonia.Utilities
return !type.IsValueType || IsNullableType(type); return !type.IsValueType || IsNullableType(type);
} }
/// <summary>
/// Returns a value indicating whether null can be assigned to the specified type.
/// </summary>
/// <typeparam name="T">The type</typeparam>
/// <returns>True if the type accepts null values; otherwise false.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool AcceptsNull<T>()
{
return default(T) is null;
}
/// <summary> /// <summary>
/// Returns a value indicating whether value can be casted to the specified type. /// Returns a value indicating whether value can be casted to the specified type.
/// If value is null, checks if instances of that type can be null. /// If value is null, checks if instances of that type can be null.
@ -102,7 +114,7 @@ namespace Avalonia.Utilities
/// <returns>True if the cast is possible, otherwise false.</returns> /// <returns>True if the cast is possible, otherwise false.</returns>
public static bool CanCast<T>(object value) public static bool CanCast<T>(object value)
{ {
return value is T || (value is null && AcceptsNull(typeof(T))); return value is T || (value is null && AcceptsNull<T>());
} }
/// <summary> /// <summary>

Loading…
Cancel
Save