C# 获取可为空的日期时间 ToString 格式方法,其中包含用于设置 Expression.Call 的参数



我正在尝试动态构建一个表达式 LINQ 函数,当我对日期时间进行字符串比较时,我得到了带有格式参数ToString方法:

else if (member.Type == typeof(DateTime))
{
var toString = typeof(DateTime).GetMethod("ToString", new Type[] { typeof(string) });
member = Expression.Call(member, toString, Expression.Constant("yyyyMMdd"));
} 

我需要获取ToStringDateTime?格式方法。

我建议构建一个这样的表达式;

Expression<Func<T?, string>> expr = d => d.HasValue ? d.Value.ToString("...") : null;

例如;

private static Dictionary<Type,string> Formats = ...
private Expression ToString(Expression value)
{
if (value.Type.IsGenericType && value.Type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
return Expression.Condition(
Expression.Property(value, "HasValue"),
ToString(Expression.Property(value, "Value")),
Expression.Constant(null, typeof(string))
);
}
var toString = value.Type.GetMethod("ToString", new Type[] { typeof(string) });
return Expression.Call(value, toString, Expression.Constant(Formats[value.Type]));
}

我不太确定您粘贴的代码块的相关性是什么; 是你说"这适用于日期时间,但不适用于日期时间?"还是你说"这就是我想用我的日期时间做的事情?"?

因此,我不能真正告诉你该怎么做,但我可以指出你会遇到的几个问题:

  • 如果您的member.Type返回一种类型的DateTime?它永远不会等于typeof(DateTime)因为它们是不同的类型。此外,我不确定member.Type如何获得值,但如果它是通过someInstance.GetType()您应该记住,在空可空对象上调用GetType()会引发空引用异常。请参阅 GetType on Nullable Boolean 以获取有关此内容的冗长讨论
  • DateTime?没有ToString(string format)过载。您可能需要实现一些东西来检查member.Type是否为可为空的类型,然后使用可为空的类型执行工作。取而代之的是值..

这里有一个小例子,上面有一个DateTime?。您必须处理值为空的情况,在这种情况下调用ToString()是没有意义的。

public class Program
{
public static void Main(string[] args)
{
DateTime? dateTime = ...;
string result = "";
if (dateTime.HasValue)
{
ConstantExpression constant = Expression.Constant(dateTime);
MethodInfo? toString = typeof(DateTime).GetMethod("ToString", new[] { typeof(string) });
MethodCallExpression call = Expression.Call(constant, toString, Expression.Constant("yyyyMMdd"));
result = Expression.Lambda<Func<string>>(call).Compile()();
}
Console.WriteLine(result);
}
}

最新更新