在Unity中使用C#进行Xml序列化时保留特定小数位的方法参考

序列化方法代码参考:

cs 复制代码
using System.IO;
using System.Xml.Serialization;

public class XmlTool
{
	public static string ToXml<T>(T obj)
	{
		XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
		using var stringWriter = new StringWriter();
		//让xml文档的命名空间为空,文档显得简洁那么一点点。
		XmlSerializerNamespaces xmlns = new XmlSerializerNamespaces();
		xmlns.Add("","");
		//
		xmlSerializer.Serialize(stringWriter, obj, xmlns);
		return stringWriter.ToString();
	}
	public static T FromXml<T>(string xml)
	{
		XmlSerializer xmlSerializer = new(typeof(T));
		return (T)xmlSerializer.Deserialize(new StringReader(xml));
	}
}

小数位数控制参考:

cs 复制代码
public struct SceneAreaInfo
{
	[XmlAttribute("X")]
	public string strX
	{
		get { return x.ToString("0.##"); }
		set { x = float.Parse(value); }
	}
	[XmlIgnore]
	public float x;//场景区域最左侧坐标

	[XmlAttribute("Y")]
	public string strY
	{
		get { return y.ToString("0.##"); }
		set { y = float.Parse(value); }
	}
	[XmlIgnore]
	public float y;//场景区域最下面坐标

	[XmlAttribute("Width")]
	public string strWidth
	{
		get { return width.ToString("0.##"); }
		set { width = float.Parse(value); }
	}
	[XmlIgnore]
	public float width;//场景区域宽度

	[XmlAttribute("Height")]
	public string strHeight
	{
		get { return height.ToString("0.##"); }
		set { height = float.Parse(value); }
	}
	[XmlIgnore]
	public float height;//场景区域高度

	[XmlIgnore]
	public Vector2 size => new Vector2(width, height);

	public SceneAreaInfo(float x, float y, float width, float height)
	{
		this.x = x;
		this.y = y;
		this.width = width;
		this.height = height;
	}
	public SceneAreaInfo(Rect rect)
	{
		x = rect.x;
		y = rect.y;
		width = rect.width;
		height = rect.height;
	}
}
相关推荐
DaLiangChen8 小时前
Vuforia 地面识别案例
unity·ar
猿长大人9 小时前
C# | JSON 序列化中的多态接口处理:基于 Attribute 实现精准 $type 控制
c#·json
Source.Liu9 小时前
【Uppsala】入口模块(lib.rs)
xml·rust
一位狮子座的程序员13 小时前
如何用RAG解决AI智能体的知识盲区?
开发语言·c#
Source.Liu13 小时前
【Uppsala】介绍
xml·rust
Nemo_XP14 小时前
C# gridlookupedit选中内容重复还原操作
服务器·前端·c#
猿长大人15 小时前
C# | 函数式编程入门
开发语言·c#·.net
江畔柳前堤15 小时前
YOLO 目标检测全流程深度剖析
人工智能·yolo·目标检测·计算机视觉·unity·面试·vllm
Wang's Blog16 小时前
AI Agent白手起家37: LangChain 输出解析器实战:文本、JSON、XML 与 Pydantic
xml·langchain·json
unityのkiven17 小时前
C# 中的奇异递归模板模式:MonoSingleton<T> 的实现
java·开发语言·c#