如果需要,我可以将可空类型的任意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