C#动态创建单例类的对象
程序员文章站
2022-05-28 21:15:24
单例类public class SnappingClass : ISnappingEnvironment, IExtension { // private static readonly SnappingClass instance = null; static SnappingClass() { ... ......
单例类
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)); } }
-----------------------------------------------------------------------------------------