在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;
	}
}
相关推荐
yangshuquan6 小时前
关于 C# 函数参数修饰符 out 和 in 的真相
c#·参数·in·修饰符·out
B0URNE6 小时前
【Unity基础详解】(11)Unity核心:输入系统
unity·游戏引擎
全栈师6 小时前
C#中控制权限的逻辑写法
开发语言·c#
夏霞7 小时前
c# 使用vs code 创建.net8.0以及.net6.0 webApi项目的教程
开发语言·c#·.net
故事不长丨8 小时前
C#线程的使用
java·microsoft·c#
小小8程序员8 小时前
C# XAML中x:Type的用法详解
开发语言·ui·c#
世洋Blog8 小时前
Unity开发微信小游戏-减少WASM包体大小
unity·游戏引擎·wasm·微信小游戏
周杰伦fans8 小时前
在C#中,`StringContent` 是 `HttpContent` 的一个派生类
开发语言·数据库·c#
TO_ZRG9 小时前
Unity 通过 NativePlugin 接入Android SDK 指南
android·unity·游戏引擎
苦荞米9 小时前
异步方法-C#中坑最大最深的功能
开发语言·c#