代码之家  ›  专栏  ›  技术社区  ›  Kyle

如何动态创建没有无参数构造函数的类的实例?

  •  1
  • Kyle  · 技术社区  · 14 年前

    我正在尝试这样的扩展方法:

    public static T Optional<T>(this T obj)
    {
        return obj != null ? obj : Activator.CreateInstance<T>();
    }
    

    但是,如果类型没有无参数构造函数,则失败。有没有一种方法可以在没有无参数构造函数的情况下获取对象的实例?

    where T : new() 并将该方法限制为仅具有无参数构造函数的类。

    2 回复  |  直到 14 年前
        2
  •  0
  •   Jeff Mercado    14 年前

    public static class Factories
    {
        public static Func<T> GetInstanceFactory<T>(params object[] args)
        {
            var type = typeof(T);
            var ctor = null as System.Reflection.ConstructorInfo;
            if (args != null && args.Length > 0)
                ctor = type.GetConstructor(args.Select(arg => arg.GetType()).ToArray());
            if (ctor == null)
                ctor = type.GetConstructor(new Type[] { });
            if (ctor == null)
                throw new ArgumentException("Cannot find suitable constructor for object");
            return () => (T)ctor.Invoke(args.ToArray());
        }
    }
    
    // usage
    var oooooFactory = Factories.GetInstanceFactory<string>('o', 5); // create strings of repeated characters
    oooooFactory(); // "ooooo"