擴充方法(Extension Method)

  • 531
  • 0
  • 2016-04-22

摘要:[.NET][C#] 擴充方法(Extension Method)


    public static class JsonConverter
    {
        /// <summary>
        /// convert Json string to Entity Use Json.Net
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonString"></param>
        /// <returns></returns>
        public static T ToEntity<T>(this string jsonString)
        {
            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(jsonString);
        }

        /// <summary>
        /// convert Entity to Json string Use Json.Net
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static string ToJsonString<T>(this T entity)
        {
            return Newtonsoft.Json.JsonConvert.SerializeObject(entity);
        }
    }

    public class test
    {
        public void main()
        {
            SampleClass1 c1 = new SampleClass1();
            string str = c1.ToJsonString();
            SampleClass1 c2 = str.ToEntity<SampleClass1>();
        }
    }