[C#] 移除物件Property

2013-02-05


在寫網頁提供Service的時候,有時候對方不需要這麼多資訊,所以有些Property 必須拿掉
該怎麼做會比較方便呢?
當然你大可重新製作一個物件,但是東西一多就是有點麻煩,我..很怕麻煩..

這時候該怎麼辦呢?
範例說明:

public class User

{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Desc { get; set; }

}






這物件透過JSON.net 輸出時我不想要輸出Desc 這Property

這時候我先將他轉成dynamic 物件




/// <summary>
/// 轉成可以擴充的物件
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static dynamic ToDynamic(object obj)
{
    IDictionary<string, object> result = new ExpandoObject();
 
    foreach (PropertyDescriptor pro in TypeDescriptor.GetProperties(obj.GetType()))
    {
        result.Add(pro.Name, pro.GetValue(obj));
    }

    return result as ExpandoObject;
}





//測試物件

var user = new User { Id = "no2don", Desc = "測試", Name = "許當當" };
 
//轉dynamic 
var dynamicUser = (IDictionary<string, object>)ToDynamic(user);
dynamicUser.Remove("Desc");

//透過json.net 印出JSON 
Response.Write(JsonConvert.SerializeObject(dynamicUser));




首先先轉成IDictionary物件,之後就可以用Key Value 的概念,將該Property 給移除..之後再輸出..



結果:



2013-02-05_125847



不太難而且很方便,給有遇到一樣的問題的人..

Source Download:


當麻許的超技八 2014 | Donma Hsu Design.