C#Assembly中的CreateInstance和Activator 中的CreateInstance

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

    [Serializable]
    [ClassInterface(ClassInterfaceType.None)]
    [ComDefaultInterface(typeof(_Assembly))]
    [ComVisible(true)]
    [__DynamicallyInvokable]
    [PermissionSet(SecurityAction.InheritanceDemand, Unrestricted = true)]
    public abstract class Assembly : _Assembly, IEvidenceFactory, ICustomAttributeProvider, ISerializable
{
        public object CreateInstance(string typeName)
        {
            return CreateInstance(typeName, ignoreCase: false, BindingFlags.Instance | BindingFlags.Public, null, null, null, null);
        }

        public virtual object CreateInstance(string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes)
        {
            Type type = GetType(typeName, throwOnError: false, ignoreCase);
            if (type == null)
            {
                return null;
            }

            return Activator.CreateInstance(type, bindingAttr, binder, args, culture, activationAttributes);
        }
}

         Activator 中的CreateInstance。

    [ClassInterface(ClassInterfaceType.None)]
    [ComDefaultInterface(typeof(_Activator))]
    [ComVisible(true)]
    [__DynamicallyInvokable]
    public sealed class Activator : _Activator
    {
     
        [MethodImpl(MethodImplOptions.NoInlining)]
        [SecuritySafeCritical]
        public static object CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes)
        {
            if ((object)type == null)
            {
                throw new ArgumentNullException("type");
            }

            if (type is TypeBuilder)
            {
                throw new NotSupportedException(Environment.GetResourceString("NotSupported_CreateInstanceWithTypeBuilder"));
            }

            if ((bindingAttr & (BindingFlags)255) == 0)
            {
                bindingAttr |= BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance;
            }

            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"));
                }
            }

            RuntimeType runtimeType = type.UnderlyingSystemType as RuntimeType;
            if (runtimeType == null)
            {
                throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "type");
            }

            StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
            return runtimeType.CreateInstanceImpl(bindingAttr, binder, args, culture, activationAttributes, ref stackMark);
        }
 }

         示例:

        以下示例定义类 Person 并调用 CreateInstance(String) 方法来实例化它。

using System;
using System.Reflection;
using Contoso.Libraries;

namespace Contoso.Libraries
{
   public class Person
   {
      private string _name;

      public Person()
      { }

      public Person(string name)
      {
         this._name = name;
      }

      public string Name
      { get { return this._name; }
        set { this._name = value; } }

      public override string ToString()
      {
         return this._name;
      }
   }
}

public class Example
{
   public static void Main()
   {
      Assembly assem = typeof(Person).Assembly;
      Person p = (Person) assem.CreateInstance("Contoso.Libraries.Person");
      if (! (p == null)) {
         p.Name = "John";
         Console.WriteLine("Instantiated a {0} object whose value is '{1}'",
                           p.GetType().Name, p);
      }
      else {
         Console.WriteLine("Unable to instantiate a Person object.");
      }
   }
}
// The example displays the following output:
//        Instantiated a Person object whose value is 'John'

 

  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值