Pass An Instantiated System.Type as a Type Parameter for a Generic Class

后端 未结 6 1297
萌比男神i
萌比男神i 2020-11-21 07:46

The title is kind of obscure. What I want to know is if this is possible:

string typeName = ;
Type myType = Type.GetType(         


        
6条回答
  •  清歌不尽
    2020-11-21 08:03

    If you know what types will be passed you can do this without reflection. A switch statement would work. Obviously, this would only work in a limited number of cases, but it'll be much faster than reflection.

    public class Type1 { }
    
    public class Type2 { }
    
    public class Generic { }
    
    public class Program
    {
        public static void Main()
        {
            var typeName = nameof(Type1);
    
            switch (typeName)
            {
                case nameof(Type1):
                    var type1 = new Generic();
                    // do something
                    break;
                case nameof(Type2):
                    var type2 = new Generic();
                    // do something
                    break;
            }
        }
    }
    

提交回复
热议问题