经常会遇到这种情况,先把字符串解析成float或者int,bool之类的,或者先把json字符串解析成对象再作为方法的参数使用,总要写一些重复性的代码,为了避免这个问题,搞了这个类,目前用起来还行。
好吧,就是这些代码,放这里算是个备份,呵呵。
using System;
using UnityEngine;
using UnityEngine.Events;
public class ParseExecute
{
static public void Float(string strValue, UnityAction<float> act)
{
float val;
if (float.TryParse(strValue, out val))
{
act?.Invoke(val);
}
else
{
Debug.Log("U3DLog:ParseExecute.Float failed,because can NOT parse " + strValue + " to float.");
}
}
static public void Int(string strValue, UnityAction<int> act)
{
int val;
if (int.TryParse(strValue, out val))
{
act?.Invoke(val);
}
else
{
Debug.Log("U3DLog:ParseExecute.Int failed,because can NOT parse " + strValue + " to int.");
}
}
static public void Bool(string strValue, UnityAction<bool> act)
{
bool val;
if (bool.TryParse(strValue, out val))
{
act?.Invoke(val);
}
else
{
Debug.Log("U3DLog:ParseExecute.Bool failed,because can NOT parse " + strValue + " to bool.");
}
}
static public void Json<T>(string json, UnityAction<T> act)
{
T t = JsonUtility.FromJson<T>(json);
if (t != null)
{
act?.Invoke(t);
}
else
{
string tName = t.GetType().Name;
Debug.Log("U3DLog:ParseExecute.Json<" + tName + "> failed,because can NOT parse " + json + " to " + tName + ".");
}
}
}