在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;
	}
}
相关推荐
工程师老罗1 小时前
YoloV1数据集格式转换,VOC XML→YOLOv1张量
xml·人工智能·yolo
暖馒1 小时前
Modbus应用层协议的深度剖析
网络·网络协议·c#·wpf·智能硬件
刘欣的博客4 小时前
C# CS架构程序发版升级的走数据库方案
c#·单文件升级自己的方式
Yorlen_Zhang6 小时前
Python Tkinter Text 控件完全指南:从基础编辑器到富文本应用
开发语言·python·c#
不绝1916 小时前
C#进阶:预处理指令/反射,Gettype,Typeof/关键类
开发语言·c#
大鹏说大话6 小时前
告别 MSBuild 脚本混乱:用 C# 和 Nuke 构建清晰、可维护的现代化构建系统
开发语言·c#
czhc11400756637 小时前
通信 28
c#
我的offer在哪里9 小时前
示例 Unity 项目结构(Playable Game Template)
unity·游戏引擎
bugcome_com11 小时前
C# 程序结构详解:从 Hello World 开始
c#
wpyok16812 小时前
密钥检测错误代码xml构建
xml