SoFunction
Updated on 2025-03-07

C# method to convert entity classes and strings

This article describes the method of C# to convert entity classes and strings into each other. Share it for your reference. The specific implementation method is as follows:

using System;
using ;
using ;
namespace 
{
 /// <summary>
 /// Convert entity classes and strings to each other /// </summary>
 public class PackReflectionEntity<T>
 {
  /// <summary>
  /// Assemble the entity class into a string by reflection  /// </summary>
  /// <param name="t">Entity class</param>  /// <returns>Assembled string</returns>  public static string GetEntityToString(T t)
  {
    sb = new StringBuilder();
   Type type = ();
   [] propertyInfos = ();
   for (int i = 0; i &lt; ; i++)
   {
    (propertyInfos[i].Name + ":" + propertyInfos[i].GetValue(t, null) + ",");
   }
   return ().TrimEnd(new char[] { ',' });
  }
  /// &lt;summary&gt;
  /// Convert the reflective string to an object  /// &lt;/summary&gt;
  /// <param name="str">Reflected string</param>  /// <returns>Entity Class</returns>  public static T GetEntityStringToEntity(string str)
  {
   string[] array = (',');
   string[] temp = null;
   Dictionary&lt;string, string&gt; dictionary = new Dictionary&lt;string, string&gt;();
   foreach (string s in array)
   {
    temp = (':');
    (temp[0], temp[1]);
   }
    assembly = (typeof(T));
   T entry = (T)(typeof(T).FullName);
    sb = new StringBuilder();
   Type type = ();
   [] propertyInfos = ();
   for (int i = 0; i &lt; ; i++)
   {
    foreach (string key in )
    {
     if (propertyInfos[i].Name == ())
     {
      propertyInfos[i].SetValue(entry, GetObject(propertyInfos[i], dictionary[key]), null);
      break;
     }
    }
   }
   return entry;
  }
  /// &lt;summary&gt;
  /// Type of conversion value  /// &lt;/summary&gt;
  /// &lt;param name="p"&gt;&lt;/param&gt;
  /// &lt;param name="value"&gt;&lt;/param&gt;
  /// &lt;returns&gt;&lt;/returns&gt;
  static object GetObject( p, string value)
  {
   switch (().ToLower())
   {
    case "int16":
     return Convert.ToInt16(value);
    case "int32":
     return Convert.ToInt32(value);
    case "int64":
     return Convert.ToInt64(value);
    case "string":
     return (value);
    case "datetime":
     return (value);
    case "boolean":
     return (value);
    case "char":
     return (value);
    case "double":
     return (value);
    default:
     return value;
   }
  }
 }
}

I hope this article will be helpful to everyone's C# programming.