dimanche 12 avril 2020

.NET Core Load generic class from string [duplicate]

In some class we have this method that suppose create an instance of any class by giving their namespace/class, for example: "App.Formats.Json.JsonFormat".

private object CreateInstanceOf(string cls)
{
    Type t = Type.GetType(cls);
    return Activator.CreateInstance(t);
}

Below is the class that need to instance from reflection, but the above method returns null when run Type.GetType...

   public class JsonFormat<T> : IFormat<T>
    {
        public JsonFormat()
        {
        }

        public string Parse(T content)
        {
            string result;

            try
            {
                result = JSONUtility<T>.ToJSON(content);
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return result ?? "";
        }
    }




Aucun commentaire:

Enregistrer un commentaire