c# - 类型和获取类型

标签 c#

我在下面序列化了一个类,该方法需要对象类型作为参数。

string xml = SerializeObject(data, typeof(ClassData));

我认为第二个参数不是必需的。如何删除第二个参数? 如何获取 data 的类型作为 Type

最佳答案

你可以这样做:

data.GetType()

这将为您提供数据

的类型

整个表达式将是

string xml = SerializeObject(data, data.GetType());

GetType() 是在 Object 上声明的方法,可用于对象的实例

typeof() 是一个语句,可以在 Type 上使用而无需它的实例。

// Get type from instance
Type type = data.GetType()

// Get type from Type
Type type = typeof(ClassData)

关于c# - 类型和获取类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5325124/

相关文章:

c# - 如何在每天指定时间执行Windows服务

c# - 我错过了什么? RestSharp 不会反序列化 Json

c# - 标签滚动效果

c# - NETCore 2.1 - 无法访问mssql服务器/SqlExeption : Cannot open database "DbName" requested by the login.登录失败

c# - 动态创建具有一列作为超链接的数据表

c# - 从 UTF8 获取字符串(无效的 URI : There is an invalid sequence in the string)

c# - 安装过程中如何创建文件夹?

c# - 出于好奇——有没有更好的方法来替换这个字符串?

c# - 如何使用 LibGit2Sharp 在 Git 上获取文件内容?

c# - ASP.NET Identity 2 邮箱和用户名分离并使用邮箱登录