[英]C# get nullable datetime ToString format method with params to set Expression.Call
我正在嘗試動態構建表達式 LINQ function,當我對日期時間進行字符串比較時,我得到了帶有格式參數的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"));
}
我需要獲取DateTime?
的ToString
格式方法嗎? .
我建議建立一個像這樣的表達式;
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]));
}
這是一個帶DateTime?
. 您必須處理值為 null 的情況,在這種情況下調用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);
}
}
我不太確定您粘貼的代碼塊的相關性是什么; 你是說“這適用於 DateTime 但不適用於 DateTime?” 還是您說“這就是我要對我的 DateTime 做的事情?”?
因此,我不能真正告訴你該怎么做,但我可以指出你會遇到的幾個問題:
member.Type
返回一個DateTime?
它永遠不會等於typeof(DateTime)
因為它們是不同的類型。 此外,我不確定member.Type
是如何產生值的,但如果它是通過someInstance.GetType()
你應該記住在 null 可空值上調用GetType()
會引發 null 引用異常。 請參閱可空 Boolean 上的 GetType 以獲得關於此的冗長論述DateTime?
沒有ToString(string format)
重載。 您可能需要實現一些檢查member.Type
是否為可空類型,然后使用可空的.Value 來代替..
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.