在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;
	}
}
相关推荐
阿蒙Amon2 小时前
C#封装HttpClient:HTTP请求处理最佳实践
开发语言·http·c#
ghost1435 小时前
C#学习第29天:表达式树(Expression Trees)
开发语言·c#
安木夕15 小时前
C#-Visual Studio宇宙第一IDE使用实践
前端·c#·.net
gregmankiw18 小时前
C#调用Rust动态链接库DLL的案例
开发语言·rust·c#
XR-AI-JK18 小时前
Unity VR/MR开发-VR/开发SDK选型对比分析
unity·vr·mr
阿蒙Amon19 小时前
06. C#入门系列【自定义类型】:从青铜到王者的进阶之路
开发语言·c#
钢铁男儿1 天前
C# 表达式和运算符(表达式和字面量)
开发语言·c#
林鸿群1 天前
C#子线程更新主线程UI及委托回调使用示例
开发语言·c#
o0向阳而生0o1 天前
63、.NET 异常处理
c#·.net·异常处理