可能问的不是很明白,解释一下:
比如,我想有一个Create方法,声明成这样了:
object Create(Type t)现在想问的是:怎样定义这个Create以实现当t不同时返回不同的实例。比如传入t=typeof(xxx)就return 一个XXX的实例指教

解决方案 »

  1.   

    实际上你是可以ruturn XXX类型的。
    只不过你return之后还是object的,在其他地方调用Create(t)的时候,返回的还是object类型,你可以进行转换。
    如果要想直接return其他类型,我认为是不行的。你的函数的返回类型已经被你定义成object了,你说是吗?
      

  2.   

    楼主,请使用System.Activator.CreateInstance(Type type)方法。
      

  3.   

    上msdn查了一下,还是猩猩比较牛*
      

  4.   

    try
            {
                Type  myType = typeof(MyClass1);
                Type[] types = new Type[1];
                types[0] = typeof(int);
                // Get the public instance constructor that takes an integer parameter.
                ConstructorInfo constructorInfoObj = myType.GetConstructor(
                    BindingFlags.Instance | BindingFlags.Public, null,
                    CallingConventions.HasThis, types, null);
                if(constructorInfoObj != null)
                {
                    Console.WriteLine("The constructor of MyClass1 that is a public " +
                        "instance method and takes an integer as a parameter is: ");
                    Console.WriteLine(constructorInfoObj.ToString());
                }
                else
                {
                    Console.WriteLine("The constructor of MyClass1 that is a public instance " +
                        "method and takes an integer as a parameter is not available.");
                }
            }
            catch(ArgumentNullException e)
            {
                Console.WriteLine("ArgumentNullException: " + e.Message);
            }
            catch(ArgumentException e)
            {
                Console.WriteLine("ArgumentException: " + e.Message);
            }
            catch(SecurityException e)
            {
                Console.WriteLine("SecurityException: " + e.Message);
            }
            catch(Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
      

  5.   

    return Activator.CreateInstance(typeof(typeName), object[] args);