C#动态创建单例类的对象

单例类

public class SnappingClass : ISnappingEnvironment, IExtension
    {
       
        //
        private static readonly SnappingClass instance = null;
        static SnappingClass()
        {
            instance = new SnappingClass();            
        }

        private SnappingClass()
        {
            
        }

        public static SnappingClass Instance
        {
            get
            {
                return instance;
            }
        }


动态创建:

void IExtensionManagerAdmin.StartupExtensions(string componentCategory, string jitCategory, ref object initializationData)
        {
            var typeInfos = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(IExtension)))).ToArray();
            foreach (var typeInfo in typeInfos)
            {
                //Console.WriteLine(typeInfo.FullName);
                //IExtension pExtension = typeInfo.Assembly.CreateInstance(v.FullName) as IExtension;

                //MethodInfo methodInfo = typeInfo.GetMethod("Instance", BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { }, null);
                //IExtension pExtension = methodInfo.Invoke(null, null) as IExtension;
                //
                PropertyInfo propertyInfo = typeInfo.GetProperty("Instance", BindingFlags.Public |  BindingFlags.NonPublic | BindingFlags.Static);
                //
                //PropertyInfo[] propertyInfos = typeInfo.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
                //foreach (PropertyInfo propertyInfo in propertyInfos)
                //{
                //    Console.WriteLine(propertyInfo.Name);
                //}
                IExtension pExtension = propertyInfo.GetValue(null, null) as IExtension;
                //
                pExtension.Startup(ref initializationData);
                this.pExtensionList.Add(new KeyValuePair<string, IExtension>(pExtension.Name, pExtension));
            }
        }

-----------------------------------------------------------------------------------------

C#动态创建单例类的对象

上一篇:C# 中indexOf、lastIndexOf、subString方法的理解


下一篇:mvc api 关于 post 跟get 请求的一些想法[FromUri] 跟[FromBody] 同一个控制器如何实现共存