如果需要,我可以將可空類型的任意convert變量設置爲不可爲空,並且可以爲類型重新定義默認值。我爲它編寫了泛型靜態類,但不幸的是,它的工作速度很慢。這個類將用於從數據庫讀取數據到模型,因此性能非常重要。這是我的班。可空類型不可爲空
public static class NullableTypesValueGetter<T> where T : struct
{
#region [Default types values]
private static DateTime currentDefaultDateTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
#endregion
#region [Default types to string values]
private const string nullableDateTimeValue = "DateTime?";
#endregion
public static T GetValue(dynamic value)
{
if (Nullable.GetUnderlyingType(value.GetType()) != null) //if variable is nullable
{
var nullableValue = value as T?;
//if variable has value
if (nullableValue.HasValue)
{
return nullableValue.Value;
}
//if hasn't
else
{
var result = default(T);
//extensionable code, determination default values
var @switch = new Dictionary<Type, string>
{
{typeof(DateTime?), nullableDateTimeValue}
};
//redefining result, if required
if (@switch.Any(d => d.Key.Equals(nullableValue.GetType())))
{
switch (@switch[nullableValue.GetType()])
{
//extensionable code
case (nullableDateTimeValue):
{
result = GetDefaultDateTimeValue();
} break;
}
}
return result;
}
}
//if not nullable
else
{
return value;
}
}
private static T GetDefaultDateTimeValue()
{
return (T)Convert.ChangeType(new DateTime?(currentDefaultDateTime), typeof(T));
}
}
你知道這個類的任何其他實現或任何提高性能的方法嗎?
當然好慢。你正在使用'dynamic',這意味着你每次運行時都要重新編譯所有的代碼。不要這樣做,特別是當你沒有理由這麼做的時候。 – Servy
'static T GetValue(Nullable nullable){return nullable.HasValue? nullable.Value:default(T); }'並且每個靜態T GetValue(object obj){if(obj.GetType()== typeof(Nullable <>))返回GetValue(可爲空值)obj);其他...你的東西與字典' –
如果你想從數據庫的值轉換爲對象,也許Dapper是一個很好的和快速的解決方案:https://github.com/StackExchange/dapper-dot-net將使它更容易處理所有的東西,你需要更少的樣板。每個其他的ORM映射器也可以工作。 – Sebi