对于类型转换,不需要再判断空值,扩展下方法,简单直接。
using UnityEngine;
using System.Collections.Generic;
//扩展方法
public static class ShortcutExtensions
{
public static TValue DicTryGetValue<Tkey, TValue>(this Dictionary<Tkey, TValue> value, Tkey key, TValue @default = default(TValue))
{
TValue result;
if(!value.TryGetValue(key, out result))
{
result = @default;
}
return result;
}
public static int IntTryParse(this object value, int @default = 0)
{
int result = 0;
if (!int.TryParse(value.ToString(), out result))
{
result = @default;
}
return result;
}
public static float FloatTryParse(this object value, float @default = 0f)
{
float result = 0;
if (!float.TryParse(value.ToString(), out result))
{
result = @default;
}
return result;
}
public static bool BoolTryParse(this object value, bool @default = false)
{
bool result = false;
if(!bool.TryParse(value.ToString(), out result))
{
result = @default;
}
return result;
}
public static long LongTryParse(this object value, long @default = 0)
{
long result = 0;
if (!long.TryParse(value.ToString(), out result))
{
result = @default;
}
return result;
}
public static double DoubleTryParse(this object value, long @default = 0)
{
double result = 0;
if (!double.TryParse(value.ToString(),out result))
{
result = @default;
}
return result;
}
}