2016-07-22 75 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