public static void Register() { // register a delegate with the Factory class that will construct an instance of this class using an array of arguments Factory.Register <PrivateConstructorExample>((args) => { if (args == null || args.Length != 3) { throw new ArgumentException("Expected 3 arguments.", "args"); } if (!(args[0] is int)) { throw new ArgumentException("First argument must be of type System.Int32.", "args[0]"); } if (!(args[1] is string)) { throw new ArgumentException("Second argument must be of type System.String.", "args[1]"); } if (!(args[2] is float)) { throw new ArgumentException("Third argument must be of type System.Single.", "args[2]"); } var instance = new PrivateConstructorExample(); instance._A = (int)args[0]; instance._B = (string)args[1]; instance._C = (float)args[2]; return(instance); }); }
static void Main(string[] args) { var factory1 = new DynamicConstructorFactory <DefaultConstructorExample>(null); var command1 = new CreateCommand <DefaultConstructorExample>(factory1); var factory2 = new DynamicConstructorFactory <NoDefaultConstructorExample>(3); factory2.Args[0] = 5; factory2.Args[1] = "ABC"; factory2.Args[2] = 7.1f; var command2 = new CreateCommand <NoDefaultConstructorExample>(factory2); PrivateConstructorExample.Register(); // register this class so that it can be created by the Factory.CreateMyType function var factory3 = new MyTypeFactory <PrivateConstructorExample>(3); factory3.Args[0] = 5; factory3.Args[1] = "ABC"; factory3.Args[2] = 7.1f; var command3 = new CreateCommand <PrivateConstructorExample>(factory3); VerifySerializability <DefaultConstructorExample>(command1); VerifySerializability <NoDefaultConstructorExample>(command2); VerifySerializability <PrivateConstructorExample>(command3); }