在 C# 中将强类型转换为匿名类型的简洁方法
Neat approach to Cast Strongly Type to Anonymous Type in C#
跟进 this 个问题。
我想从 Strongly Typed
转换为 Anonymous Type
结果。例如,以下 class 应在 运行 时间内转换为匿名类型对象。正在努力实现这一目标。
public sealed class CountryModel
{
public int CountryId { get; set; }
public string CountryName { get; set; }
public string CountryCode { get; set; }
public bool IsActive { get; set; }
}
用法:
new CountryModel()
{
CountryCode = "AOE",
CountryId = 2,
CountryName = "Anywhere on Earth",
IsActive = true
};
匿名类型:
上面的强类型应转换为匿名,最终结果将如下所示(通过立即 Window 捕获):
{ CountryId = 2, CountryName = "Anywhere on Earth", CountryCode = "AOE", IsActive = true }
CountryCode: "AOE"
CountryId: 2
CountryName: "Anywhere on Earth"
IsActive: true
注意:我需要完成此转换,以便我可以将对象传递给 Dapper.SimpleCRUD 和 Dapper ORM 库。
试试这个:
var obj = new {
CountryCode = item.CountryCode,
CountryId = item.CountryId,
CountryName = item.CountryName,
IsActive = item.IsActive
};
跟进 this 个问题。
我想从 Strongly Typed
转换为 Anonymous Type
结果。例如,以下 class 应在 运行 时间内转换为匿名类型对象。正在努力实现这一目标。
public sealed class CountryModel
{
public int CountryId { get; set; }
public string CountryName { get; set; }
public string CountryCode { get; set; }
public bool IsActive { get; set; }
}
用法:
new CountryModel()
{
CountryCode = "AOE",
CountryId = 2,
CountryName = "Anywhere on Earth",
IsActive = true
};
匿名类型:
上面的强类型应转换为匿名,最终结果将如下所示(通过立即 Window 捕获):
{ CountryId = 2, CountryName = "Anywhere on Earth", CountryCode = "AOE", IsActive = true }
CountryCode: "AOE"
CountryId: 2
CountryName: "Anywhere on Earth"
IsActive: true
注意:我需要完成此转换,以便我可以将对象传递给 Dapper.SimpleCRUD 和 Dapper ORM 库。
试试这个:
var obj = new {
CountryCode = item.CountryCode,
CountryId = item.CountryId,
CountryName = item.CountryName,
IsActive = item.IsActive
};