get assembly by class name

后端 未结 4 1022
青春惊慌失措
青春惊慌失措 2020-12-10 12:16

Is there any way to get the assembly that contains a class with name TestClass? I just know the class name, so I can\'t create an instance of that. And

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-10 13:13

    Marc's answer is really good, but since it was too slow (I'm using that method often), I decided to go with a different approach:

        private static Dictionary types;
        private static readonly object GeneralLock = new object();
    
        public static Type FindType(string typeName)
        {
            if (types == null)
            {
                lock (GeneralLock)
                {
                    if (types == null)
                    {
                        types = new Dictionary();
                        var appAssemblies = AppDomain.CurrentDomain.GetAssemblies();
                        foreach (var appAssembly in appAssemblies)
                        {
                            foreach (var type in appAssembly.GetTypes())
                                if (!types.ContainsKey(type.Name))
                                    types.Add(type.Name, type);
                        }
                    }
                }
            }
    
            return types[typeName];
        }
    

    You can handle the name clash the way you want, but in this example I decided to just ignore the subsequent ones.

提交回复
热议问题