在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;
	}
}
相关推荐
曹牧11 小时前
C#:24小时制时间
c#
唐青枫17 小时前
别急着拆服务:C#.NET 微服务架构从边界设计到实战
c#·.net
czhc114007566321 小时前
从一份运行日志还原一次生产卡死:三个信号与一场“假卡死“
c#
Jazz_z21 小时前
如何用 C# 读取 Word 中的表格数据
开发语言·c#
执明wa1 天前
Android RecyclerView 多类型, 多种 Item
android·xml·开发语言·设计模式·android studio
阿松爱学习1 天前
【Unity开发】FileStream 详解及用法指南
unity·c#·unity开发
想做后端的前端1 天前
Unity-UIGI优化Rebatch与Rebuild
unity
wl85111 天前
SAP CPI 教程004 如何通过groovy修改XML节点属性值
xml
淡海水1 天前
12-02-性能-数据结构性能调查案例1-5
数据结构·性能优化·c#
Java的搬运工1 天前
使用 C# 轻松管理 PDF 文件的用户权限
c#·用户权限