可空类型不可为空

Дми*_*пин 0 c# generics performance

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

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));
    }
}
Run Code Online (Sandbox Code Playgroud)

您是否了解此课程的其他任何实现或任何提高此课程表现的方法?

Tim*_*ter 6

你为什么不简单地使用Nullable<T>.GetValueOrDefault

int? val = null;
int newVal = val.GetValueOrDefault(-1); // result: -1
Run Code Online (Sandbox Code Playgroud)