利用C#反射机制,将type作为泛型T传入方法

利用C#反射机制,将type作为泛型T传入方法

    public class YamlConverter
    {
     
        public object Deserializer<T>(string input)
        {
     
            object result = null;
            // DO something
            return result;
        }
    }
    public class Model
    {
     
        public string name;
        public string job;
    }
    public class Model2
    {
     
        public string name;
        public string sex;
    }
    public static class TestMap
    {
     
        // 外部函数调用此方法
        public static object Create(string id,string content)
        {
     
            Type type = TestMap.Map[id];
            YamlConverter yaml = new YamlConverter();
            MethodInfo mi = yaml.GetType().GetMethod("Deserializer").MakeGenericMethod(new Type[] {
      type });
            object[] l_args = new object[1] {
      content };
            object testContent = mi.Invoke(yaml, l_args);
            return testContent;
        }

        public static Dictionary<string, Type> Map = new Dictionary<string, Type> {
     
            {
      "001", typeof(Model) }{
      "001", typeof(Model2) }};
    }

你可能感兴趣的:(反射,c#)