2016-07-22 173 views
0

跟进来自this的问题。以强制类型转换为匿名类型的简洁方法C#

我想投从Strongly TypedAnonymous Type结果。举例来说,在运行时应将以下类转换为匿名类型对象。我努力实现这一目标。

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 
}; 

匿名类型:

上述强类型应转换为匿名和最终的结果是这样的(通过立即窗口捕获)

{ CountryId = 2, CountryName = "Anywhere on Earth", CountryCode = "AOE", IsActive = true } 
    CountryCode: "AOE" 
    CountryId: 2 
    CountryName: "Anywhere on Earth" 
    IsActive: true 

注意:我需要执行此投射操作,以便将对象传递给Dapper.SimpleCRUD和Dapper ORM库。

+3

你为什么要这么做? –

+0

它不是一个匿名对象,它可以被装箱到一个“对象”。但它不是匿名的 –

+0

添加了一个笔记给我的问题。但是,在这里你再次“需要完成这个工作,以便我可以将对象传递给Dapper.SimpleCRUD和Dapper ORM库” –

回答

2

试试这个:

var obj = new { 
    CountryCode = item.CountryCode, 
    CountryId = item.CountryId, 
    CountryName = item.CountryName, 
    IsActive = item.IsActive 
    }; 
+2

不知道为什么这 *被* downvoted;它确实*字面*所要求的东西(虽然你实际上可以使它变得更加简洁 - 只是'new {item.CountryCode,item.CountryId,...}'很好 - 它推断出这些名字)。但我脑海中的问题是,它是否有用或必要*这样做 - 这对于OP来说确实是一个问题,尽管 –

+0

不确定你在说什么。这个答案根本没有被降低。 – Yar