Pass Type parameter for generic Runtime method

Asked

Viewed 758 times

3

I have a method I use to deserialize data:

public static class CustomJson<T> where T: class, new()
{
    public static T Deserialize(string data)
    {
        try
        {
            return string.IsNullOrEmpty(data) 
                      ? default(T) 
                      : Newtonsoft.Json.JsonConvert.DeserializeObject<T>(data);
        }
        catch (Exception ex)
        {
            throw new Exceptions.SerializationException(SerializationType.Json, ex);
        }
    }
}

The type to be used in deserialization I know only in Runtime:

public void TesteCustomJson(string package, string methodName)
{
    try
    {
        var serviceFactory = new ServiceFactory();
        var service = serviceFactory.GetService<ITesteService>();

        var method = service.GetType().GetMethod(methodName);
        if (method != null)
        {
            var parameter = method.GetParameters().FirstOrDefault();
            if (parameter != null)
            {
                var parameterType = parameter.ParameterType;
                var result = Framework.Utils.Serialization.CustomJson<parameterType>.Deserialize(package);
            }
        }
    }
    catch (Exception ex)
    {
        Debug.WriteLine(ex);
    }
}

Doing so does not compile, the following error is generated:

The type or namespace name 'parameterType' could not be found (are you Missing a using Directive or an Assembly Reference?)

Is there any way to pass the kind to be deserialized knowing it only at runtime?

  • Why do you only know in Runtime? Are you sure of this? From the section posted this is not clear. Beyond this. Do you really want a memory error or other error reported as a serialization error? http://answall.com/a/30168/101

  • I actually know the types, but how can I treat them in a generic way when there are hundreds of different types? I think that if we take the type in Runtime could be less laborious. As for the error treatment, we will improve it, here was just an example.

  • If you know the type at compile time, you should deal with it at compile time. The path was correct. Maybe the problem is in the use but you have not posted relevant information of how you are using. Since I haven’t seen all the code you can’t say but I think you know what kind of parameter, then use this guy and be happy.

  • I posted the complete test method.

  • 2

    http://stackoverflow.com/a/232621/4322614

  • Thanks @Matthew, corresponds with the reply of Omni.

  • Yes @Paulobalbino, I found this solution in the OS, but when I went to see had already answered, not to miss the trip posted what I found.

Show 2 more comments

1 answer

4


You can use the following code to pass a generic type during Runtime:

public static class CustomJson<T> where T : class, new()
{
    public static T Deserialize(string data)
    {
        try
        {
            if (string.IsNullOrEmpty(data)) 
                return new T();
            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(data);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            throw;
        }
    }
}

public class TestClass
{
    public int Id { get; set; }

    public TestClass()
    {
    }
}

public void TestGeneric()
{
    Type custom = typeof(CustomJson<>);
    Type newInstance = custom .MakeGenericType(typeof(TestClass));
    MethodInfo mi = newInstance.GetMethod("Deserialize");
    var res = mi.Invoke(null, new object[] { "{Id: 3}" });
}

Pay attention to the method .MakeGenericType. Summarily, the method creates a new CustomJson<T> with the types provided in the method. Although here it is replaced only T, the same could be applied to more generic types.

Example in Dotnetfiddle.

  • Thank you, I’ll do the tests.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.