C#Assembly中的CreateInstance和Activator 中的CreateInstance
创始人
2024-11-18 18:35:18

        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'

 

相关内容

热门资讯

十大便宜好用的云手机|手游党实... 家人们谁懂啊!作为常年爱多开养号、宅家玩手游的懒人,为了找一款便宜又好用的云手机,我足足实测了市面上...
银行春招,考官是AI,作弊的也... 来源:滚动播报 (来源:千龙网) “欢迎参与AI面试,每道题有思考时间,也可以直接作答。”屏幕里的数...
相关未来应用场景一览 从工业生产到日常生活,从城市运行到数字娱乐,边缘计算与人工智能相结合,正在解锁一个又一个全新应用场景...
OpenAI总裁:马斯克不懂A... 凤凰网科技讯 5月6日,据彭博社报道,OpenAI总裁格雷格·布罗克曼(Greg Brockman)...
苹果据悉将允许用户选用多款第三... 来源:滚动播报 苹果公司将允许用户从一系列外部人工智能服务中进行选择,为其软件各项功能提供支持。此举...