我已经将可空类型的任务转换变量设置为不可空,如果它可以为空并且重新定义类型的默认值(如果需要的话).我为它编写了泛型静态类,但遗憾的是,它的工作速度很慢.该类将用于从数据库读取数据到模型,因此性能非常重要.这是我的课.
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 …Run Code Online (Sandbox Code Playgroud)