PDA

View Full Version : چگونه میشود از یوزر کنترلی که نوع آن به صورت استرینگ پاس داده شده new کرد؟



computer-mag
سه شنبه 17 دی 1392, 09:04 صبح
سلام خسته نباشید کد زیر را در نظر بگیرید:

UserControlAdd n = new UserControlAdd();


من می خوام این کد رو جوری بنویسم که قسمت UserControlAdd() که بعد از New اومده رو از پارامتری در کانستراکتو فرم خودم بخونم یعنی هر بار این آبجکت n از یک نوع یوزرکنترل ها new شود. ممنون میشم کمکم کنید


من خودم کد زیر رو پیدا کردم ولی ارور میده اگه ارور این کد رو هم رفع کنید مشکل من حل میشه مرسی


var scan_class = "UserControlAdd";
var bindingFlags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
var constructorArgs = new object[] { "salam" };
var constructorTypes = from p in constructorArgs select p.GetType();

var type = Type.GetType(scan_class);
var method = type.GetMethod(scan_class, bindingFlags, System.Type.DefaultBinder, constructorTypes.ToArray(), null);
var myObject = method.Invoke(null, bindingFlags, System.Type.DefaultBinder, constructorArgs, CultureInfo.CurrentCulture);

flowLayoutPanel1.Controls.Add(myObject as Control);

computer-mag
سه شنبه 17 دی 1392, 17:01 عصر
دوستان کسی کمک نکرد ولی من مشکل رو حل کردم اینم روشش میزرم که اگه کسی به مشکل برخورد ازش استفاده کنه

// Get a type from the string
Type type = Type.GetType(myclass);
// Create an instance of that type
Object obj = Activator.CreateInstance(type);
// Retrieve the method you are looking for
//MethodInfo methodInfo = type.GetMethod(mymethod);
var constructorArgs = new object[] { 3 };
var constructorTypes = from p in constructorArgs select p.GetType();
ParameterModifier param = new ParameterModifier(1);

// Pass the first and third parameters by reference.
param[0] = true;


// The ParameterModifier must be passed as the single element
// of an array.
ParameterModifier[] mods = { param };
MethodInfo methodInfo = type.GetMethod(mymethod, constructorTypes.ToArray(),mods);
// Invoke the method on the instance we created above
methodInfo.Invoke(obj, constructorArgs);