110,538
社区成员
发帖
与我相关
我的任务
分享
public static T? DbValueTo<T>(object value) where T : struct
{
T? result = null;
if (value != null && !(value is DBNull))
{
result = T.Parse(value.ToString());
}
return result;
}
public class MyClass2<T>
where T : struct//这个泛型类只接受值类型的泛型参数
{
}
public class ConvertStruts
{
static ConvertStruts()
{
Cache<int>.Convert = (x) => Convert.ToInt32(x);
Cache<long>.Convert = (x) => Convert.ToInt64(x);
}
private static class Cache<TResult>
{
public static Func<object, TResult> Convert;
}
public static T? DbValueTo<T>(object value) where T : struct
{
T? result = null;
if (value != null && !(value is DBNull))
{
result = Cache<T>.Convert(value);
}
return result;
}
}
static void Main(string[] args)
{
var a = ConvertStruts.DbValueTo<int>("123");
}
这样也行,这种更好。。但你要理解下
public static T? DbValueTo<T>(object value) where T : struct
{
T? result = null;
if (value != null && !(value is DBNull))
{
result = (T?)Convert.ChangeType(value, typeof(T));
}
return result;
}
public T GetValue<T>(object value, T defaultvalue = default(T))
{
if (value== null || value== DBNull.Value)
{
return defaultvalue;
}
return (T)value;
}