C#类型获取实例

public static class ToObject<T> where T : class
{
   public static Dictionary<string, string> values = new Dictionary<string, string>();
  
   static object target;

   private static void CreateInitiate()

  {

    Type t = typeof(T);

    ConstructorInfo ct = t.GetConstructor(System.Type.EmptyTypes);

    target = (T)ct.Invoke(null);

  }

public static T ToEgg()
{

if (target != null)

{

target = null;

}

CreateInitiate();

Type t = target.GetType();

FieldInfo[] fields = t.GetFields();

string fieldName = string.Empty;

values.Add("id", "200");
values.Add("path", "Model/Image");

foreach (FieldInfo f in fields)

{

fieldName = f.Name;
Debug.Log(fieldName);
f.SetValue(target, Convert.ChangeType(values[fieldName], f.FieldType));

}
return (T)target;

}

 


}

这样就可以经过修改,把Json字符串或者xml字符串转化为类了

posted @ 2017-08-17 11:30  狂奔的老鳖  阅读(853)  评论(0编辑  收藏  举报