在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;
	}
}
相关推荐
今晚打老虎z8 小时前
解决SQL Server 安装运行时针对宿主机内存不足2GB的场景
sqlserver·c#
Traced back9 小时前
# C# WinForms 数据库清理系统基础知识与避坑指南
开发语言·数据库·c#
我要打打代码11 小时前
关于C#线程 任务
开发语言·数据库·c#
小贺儿开发11 小时前
Unity3D 八大菜系连连看
游戏·unity·互动·传统文化
在路上看风景12 小时前
25. 屏幕像素和纹理像素不匹配
unity
Traced back12 小时前
# C# 基础语法完全指南
开发语言·c#
大黄说说12 小时前
TensorRTSharp 实战指南:用 C# 驱动 GPU,实现毫秒级 AI 推理
开发语言·人工智能·c#
特立独行的猫a12 小时前
从XML到Compose的UI变革:现代(2026)Android开发指南
android·xml·ui·compose·jetpack
芳草萋萋鹦鹉洲哦12 小时前
后端C#,最好能跨平台,桌面应用框架如何选择?
开发语言·c#
ۓ明哲ڪ13 小时前
Unity功能——创建新脚本时自动添加自定义头注释
unity·游戏引擎