在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;
	}
}
相关推荐
攻城狮CSU3 小时前
类型转换汇总 之C#
java·算法·c#
CodeCraft Studio6 小时前
国产化Word处理控件Spire.Doc教程:用Java实现TXT文本与Word互转的完整教程
java·c#·word·spire.doc·word文档转换·txt转word·word转txt
Aevget6 小时前
DevExpress WinForms v25.1亮点 - 电子表格组件、富文档编辑器全新升级
c#·编辑器·界面控件·devexpress·ui开发·winforms
一个专注写bug的小白猿6 小时前
.net实现ftp传输文件保姆教程
后端·c#·.net
shandianchengzi9 小时前
【记录】Unity|Unity从安装到打开一个Github项目(以我的世界(仿)为例)
unity·c#·游戏引擎·github·我的世界·mc
咕白m6259 小时前
通过 C# 给Word文档添加水印:文字水印、图片水印
后端·c#
YuanlongWang11 小时前
C# 基础——async/await 的实现原理与最佳实践
开发语言·c#
kalvin_y_liu12 小时前
ManySpeech —— 使用 C# 开发人工智能语音应用
开发语言·人工智能·c#·语音识别
唐青枫12 小时前
C#.NET FluentSqlKata 全面解析:基于链式语法的动态 SQL 构建
c#·.net
加号31 天前
【C#】获取电脑网卡MAC地址
windows·c#