nullable型の変数をnullable型に変換する必要がある場合はnullable型であり、型のデフォルト値を再定義することはできません。私はそれのための一般的な静的クラスを書いたが、残念ながら、それは遅くするために働く。このクラスはデータベースからモデルにデータを読み込む際に使用されるため、パフォーマンスは非常に重要です。ここに私のクラスです。Nullable型をnullにできないようにする
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){nullを返します.HasValue? nullable.Value:デフォルト(T)。すべての '静的T GetValue(オブジェクトobj){if(obj.GetType()== typeof(Nullable <>))はGetValue(Nullable )obj)を返します。そうでなければ...辞書であなたのもの ' –
データベースからオブジェクトへの値を変換したいのであれば、Dapperはあなたにとってすばらしい、速い解決策です:https://github.com/StackExchange/dapper-dot-netあなたはそのすべてのものを扱うのが簡単で、定型会話は必要ありません。他のすべてのORM-Mapperも同様に動作します。 – Sebi