当前位置:编程学习 > C#/ASP.NET >>

C#编程的一些问题

CreateInstance() 这个方法怎么用?
追问:我是在System.Array类中 看到的CreateInstance()方法  就知道是创造数组并指定长度  可不知道怎么用
答案:Assembly.Load("MyAssembly").CreateInstance("Student");

CreateInstance()方法接受一个字符串的参数。

这个字符串是当前程序集中类的名字。

这个方法根据这个类的名字创建类的实例。

 

Student stu=Assembly.Load("MyNameSpace").CreateInstance("Student");

相当于

Student stu=new Student();

 

方法的介绍:

Assembly.CreateInstance 方法 (String)

使用区分大小写的搜索,从此程序集中查找指定的类型,然后使用系统激活器创建它的实例。

Activator.CreateInstance 方法 (Type)

使用与指定参数匹配程度最高的构造函数来创建指定类型的实例。

看完以后,忽然觉得说了跟没说一样。不知道是我文字理解能力有问题,还是它表达有问题。

于是,没办法,只好用Reflector看看源代码了。

System.Reflection.Assembly位于mscorlib.dll里,CreateInstance()方法的源码是这样的

 

System.Activator也位于mscorlib.dll里,CreateInstance()方法的

public object CreateInstance(string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes)
{
      Type type1 = this.GetTypeInternal(typeName, false, ignoreCase, false);
      if (type1 == null)
      {
            return null;
      }
      //注意一下这一句,晕。。。。这里居然调用了Activator.CreateInstance方法
      return Activator.CreateInstance(type1, bindingAttr, binder, args, culture, activationAttributes);
}

源码如下

public static object CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes)
{
      object obj1;
      if (type == null)
      {
            throw new ArgumentNullException("type");
      }
      if (type is TypeBuilder)
      {
            throw new NotSupportedException(Environment.GetResourceString("NotSupported_CreateInstanceWithTypeBuilder"));
      }
      if ((bindingAttr & ((BindingFlags) 0xff)) == BindingFlags.Default)
      {
            bindingAttr |= BindingFlags.CreateInstance | BindingFlags.Public | BindingFlags.Instance;
      }
      if ((activationAttributes != null) && (activationAttributes.Length > 0))
      {
            if (!type.IsMarshalByRef)
            {
                  throw new NotSupportedException(Environment.GetResourceString("NotSupported_ActivAttrOnNonMBR"));
            }
            if (!type.IsContextful && ((activationAttributes.Length > 1) || !(activationAttributes[0] is UrlAttribute)))
            {
                  throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonUrlAttrOnMBR"));
            }
      }
      try
      {
            obj1 = ((RuntimeType) type.UnderlyingSystemType).CreateInstanceImpl(bindingAttr, binder, args, culture, activationAttributes);
      }
      catch (InvalidCastException)
      {
            throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "type");
      }
      return obj1;
}
这个方法一般为创建对象的方法,使用工厂模式建立的类结构大多采用这种方式进行创建静态对象,使用该对象做方法处理

上一个:C#编程的问题99
下一个:2个c#编程答案

CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,