fix(module: table): formatting with nullable type for table column (#487)

This commit is contained in:
James Yeung 2020-08-10 16:05:50 +08:00 committed by GitHub
parent e2470e73cc
commit d84300651d
3 changed files with 42 additions and 3 deletions

View File

@ -1,6 +1,8 @@
using System;
using System.Linq.Expressions;
using System.Globalization;
using AntDesign.Core.Reflection;
using System.Collections.Generic;
namespace AntDesign.Helpers
{
@ -19,20 +21,28 @@ namespace AntDesign.Helpers
var p1 = Expression.Parameter(typeof(T));
var p2 = Expression.Parameter(typeof(string));
Expression variable = p1;
Expression body = p2;
if (TypeDefined<T>.IsNullable)
{
type = TypeDefined<T>.NullableType;
}
if (type.IsSubclassOf(typeof(IFormattable)))
{
var method = type.GetMethod("ToString", new[] { typeof(string), typeof(IFormatProvider) });
body = Expression.Call(Expression.Convert(p1, type), method, p2, Expression.Constant(null));
body = Expression.Call(Expression.Convert(variable, type), method, p2, Expression.Constant(null));
}
else
{
var method = type.GetMethod("ToString", new[] { typeof(string) });
if (method != null)
{
body = Expression.Call(Expression.Convert(p1, type), method, p2);
body = Expression.Call(Expression.Convert(variable, type), method, p2);
}
}
return Expression.Lambda<Func<T, string, string>>(body, p1, p2).Compile();
}
}

View File

@ -0,0 +1,29 @@
using System;
namespace AntDesign.Core.Reflection
{
internal static class TypeDefined<T>
{
public static bool IsNullable;
public static bool IsGenericType => typeof(T).IsGenericType;
public static Type NullableType;
static TypeDefined()
{
IsNullable = IsNullableType(typeof(T));
NullableType = GetNullableGenericType(typeof(T));
}
private static bool IsNullableType(Type type)
{
return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);
}
private static Type GetNullableGenericType(Type type)
{
return IsNullableType(type) ? type.GetGenericArguments()[0] : null;
}
}
}

View File

@ -74,7 +74,7 @@
public int Id { get; set; }
[DisplayName("Date")]
public DateTime Date { get; set; }
public DateTime? Date { get; set; }
[DisplayName("Temp. (C)")]
public int TemperatureC { get; set; }