获取非公共无参构造函数的类实例

来源:互联网 发布:365外勤软件下载 编辑:程序博客网 时间:2024/05/17 02:04

使用Activator:

//// Summary: // Creates an instance of the specified type using that type's default constructor. // // Parameters: // type: // The type of object to create. // // nonPublic: // true if a public or nonpublic default constructor can match; false if only // a public default constructor can match. // // Returns: // A reference to the newly created object. public static object CreateInstance(Type type, bool nonPublic);

实例:

public class Singleton<T> where T : class{private static T singleton;public static T Instance{get{if (Singleton<T>.singleton == default(T)){try{Singleton<T>.singleton = (T)Activator.CreateInstance(typeof(T), true);}catch (TargetInvocationException ex){throw ex.InnerException;}}return Singleton<T>.singleton;}}}


0 0
原创粉丝点击