当前位置: 首页>>代码示例>>C#>>正文


C# Type.GetConstructors方法代码示例

本文整理汇总了C#中Type.GetConstructors方法的典型用法代码示例。如果您正苦于以下问题:C# Type.GetConstructors方法的具体用法?C# Type.GetConstructors怎么用?C# Type.GetConstructors使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Type的用法示例。


在下文中一共展示了Type.GetConstructors方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: AddAll

 public void AddAll(Type testCaseType)
 {
     foreach (MethodInfo method in testCaseType.GetMethods()) {
         foreach (Attribute attribute in method.GetCustomAttributes(false)) {
             if (attribute != null) {
                 ConstructorInfo constructor = testCaseType.GetConstructors () [0];
                 UUnitTestCase newTestCase = (UUnitTestCase)constructor.Invoke (null);
                 newTestCase.SetTest (method.Name);
                 Add (newTestCase);
             }
         }
     }
 }
开发者ID:bdcooper,项目名称:Unity3DAI,代码行数:13,代码来源:UUnitTestSuite.cs

示例2: AddAll

 private void AddAll(Type testCaseType)
 {
     var methods = testCaseType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
     foreach (MethodInfo m in methods)
     {
         var attributes = m.GetCustomAttributes(typeof(UUnitTestAttribute), false);
         if (attributes.Length > 0)
         {
             ConstructorInfo constructor = testCaseType.GetConstructors()[0];
             UUnitTestCase newTestCase = (UUnitTestCase)constructor.Invoke(null);
             newTestCase.SetTest(m.Name);
             Add(newTestCase);
         }
     }
 }
开发者ID:MarcoWilliamsPF,项目名称:SDKGenerator,代码行数:15,代码来源:UUnitTestSuite.cs

示例3: GetInstance

    public static object GetInstance(Type T)
    {
        object Result = null;
        if (T == null) return null;
        T = WithoutRef(T);

        if (T.IsValueType)
        {
            Result = Activator.CreateInstance(T);
        }
        else if (T.Name == "String")
            Result = (object)"";
        else
        {
            ConstructorInfo C = T.GetConstructor
            (BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null);
            if (C != null) Result = C.Invoke(null);
            else
            {
                ConstructorInfo[] CC = T.GetConstructors(); int i = 0;
                while ((i < CC.Length) && (!ItGoodConstructor(CC[i]))) { i = i + 1; }
                if (i < CC.Length) Result = ObjectFromConstructor(CC[i]);

                if ((Result == null) && (CC.Length > 0))
                {
                    ParameterInfo[] ps = CC[0].GetParameters();
                    List<object> o = new List<object>();
                    object O = null;
                    for (i = 0; i < ps.Length; i++)
                    {
                        //  if ((ps[i].DefaultValue != null)&&(!ps[i].ParameterType.IsByRef)) O = ps[i].DefaultValue; else //some time not work(((
                        {
                            O = GetInstance(ps[i].ParameterType);
                            if (O == null) break;
                        }
                        o.Add(O);
                    }
                    if (o.Count == ps.Length) Result = CC[0].Invoke(o.ToArray());
                }
            }
        }
        return Result;
    }
开发者ID:Martmath,项目名称:ExtReflection_Convert,代码行数:43,代码来源:CLS_NewInstance.cs

示例4: Calculate

 public static long Calculate(Type t)
 {
     MemoryStream ms = new MemoryStream();
     BinaryWriter bw = new BinaryWriter(ms);
     bw.Write(t.FullName);
     bw.Write((int)t.Attributes);
     foreach(FieldInfo fi in t.GetFields(BindingFlags.Public |
                                         BindingFlags.NonPublic | BindingFlags.Instance).OrderBy(f => f.Name))
     {
         bw.Write(fi.Name);
         bw.Write((int)fi.Attributes);
     }
     foreach(PropertyInfo pi in
             t.GetProperties(BindingFlags.Public | BindingFlags.Instance).OrderBy(p
                                                                          => p.Name))
     {
         bw.Write(pi.Name);
         bw.Write((int)pi.Attributes);
     }
     foreach(ConstructorInfo ci in
             t.GetConstructors(BindingFlags.Public | BindingFlags.Instance).OrderBy(c
                                                                            => Signature(c.Name, c.GetParameters())))
     {
         bw.Write(Signature(ci.Name, ci.GetParameters()));
         bw.Write((int)ci.Attributes);
     }
     foreach(MethodInfo mi in t.GetMethods(BindingFlags.Public |
                                           BindingFlags.Instance | BindingFlags.Static).OrderBy(m =>
                                                          Signature(m.Name, m.GetParameters())))
     {
         bw.Write(Signature(mi.Name, mi.GetParameters()));
         bw.Write((int)mi.Attributes);
     }
     bw.Close();
     ms.Close();
     byte[] b = ms.ToArray();
     byte[] hash = sha.TransformFinalBlock(b, 0, b.Length);
     return (((long)hash[0]) << 56) | (((long)hash[1]) << 48) |
         (((long)hash[2]) << 40) | (((long)hash[3]) << 32)
             | (((long)hash[4]) << 24) | (((long)hash[5]) << 16) |
             (((long)hash[6]) <<  8) | (((long)hash[7]) <<  0);
 }
开发者ID:sailesh341,项目名称:JavApi,代码行数:42,代码来源:SerialUIDCalculator.cs

示例5: GetFactory

        /// <summary>
        /// Gets factory to create instance of type using the public parameterless ctor.
        /// Use it when you want to create many instances of the same type in different objects
        /// Aprox, 1.3x faster than Activator, almost as fast a manual if you cache and reuse the delegate
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public static Func<object> GetFactory(Type t)
        {
            Func<object> inv;      
            lock (actLock)
            {
                if (_actCache == null) _actCache = new Dictionary<Type, Func<object>>();
                if (!_actCache.TryGetValue(t,out inv))
                {
#if COREFX
                var constructor = t.GetConstructor(Type.EmptyTypes) ?? t.GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance).First();
#else
               var constructor = t.GetConstructor(Type.EmptyTypes)??t.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[0], null);
#endif
                    var body = Expression.New(constructor);
                    inv = Expression.Lambda<Func<object>>(body).Compile();
                    _actCache[t] = inv;
                }

            }

            return inv;
        }
开发者ID:sapiens,项目名称:cavemantools,代码行数:29,代码来源:TypeFactory.cs

示例6: AddTypeInfo

    public static int AddTypeInfo(Type type, out ATypeInfo tiOut)
    {
        ATypeInfo ti = new ATypeInfo();
        ti.fields = type.GetFields(JSMgr.BindingFlagsField);
        ti.properties = type.GetProperties(JSMgr.BindingFlagsProperty);
        ti.methods = type.GetMethods(JSMgr.BindingFlagsMethod);
        ti.constructors = type.GetConstructors();
        if (JSBindingSettings.NeedGenDefaultConstructor(type))
        {
            // null means it's default constructor
            var l = new List<ConstructorInfo>();
            l.Add(null);
            l.AddRange(ti.constructors);
            ti.constructors = l.ToArray();
        }
        ti.howmanyConstructors = ti.constructors.Length;

        FilterTypeInfo(type, ti);

        int slot = allTypeInfo.Count;
        allTypeInfo.Add(ti);
        tiOut = ti;
        return slot;
    }
开发者ID:wang10998588,项目名称:qjsbunitynew,代码行数:24,代码来源:GeneratorHelp.cs

示例7: ConstructCustomType

        private object ConstructCustomType(Type type, List<CodeExpression> arguments, int lparenPosition)
        {
            string message;

            // Build a list of candidate constructors.

            ConstructorInfo[] ctors = type.GetConstructors(BindingFlags.Public | BindingFlags.Instance);
            List<CandidateConstructor> candidates = GetCandidateConstructors(ctors, arguments);
            if (candidates == null || candidates.Count == 0)
            {
                message = string.Format(CultureInfo.CurrentCulture, Messages.UnknownMethod, type.Name, RuleDecompiler.DecompileType(type));
                throw new RuleSyntaxException(ErrorNumbers.Error_MethodNotExists, message, lparenPosition);
            }

            // Select the best constructor from the list of candidates.

            CandidateConstructor bestCandidate = FindBestConstructor(candidates);

            if (bestCandidate == null)
            {
                // It was ambiguous.
                message = string.Format(CultureInfo.CurrentCulture, Messages.AmbiguousConstructor, type.Name);
                throw new RuleSyntaxException(ErrorNumbers.Error_CannotResolveMember, message, lparenPosition);
            }

            // Invoke the constructor.
            object result = null;
            try
            {
                result = bestCandidate.InvokeConstructor();
            }
            catch (TargetInvocationException invokeEx)
            {
                if (invokeEx.InnerException == null)
                    throw; // just rethrow this one in the unlikely case the inner one is null.

                // Rethrow the inner exception's message as a RuleSyntaxException.
                throw new RuleSyntaxException(ErrorNumbers.Error_MethodNotExists, invokeEx.InnerException.Message, lparenPosition);
            }

            return result;
        }
开发者ID:iskiselev,项目名称:JSIL.NetFramework,代码行数:42,代码来源:Parser.cs

示例8: GetAllConstructors

        static ConstructorInfo [] GetAllConstructors (Type t)
        {
                BindingFlags static_flag = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly |BindingFlags.Static;
                BindingFlags instance_flag = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly |BindingFlags.Instance;

                ConstructorInfo [] static_members = t.GetConstructors (static_flag);
                ConstructorInfo [] instance_members = t.GetConstructors (instance_flag);

                if (static_members == null && instance_members == null)
                        return null;

                ConstructorInfo [] all_members = new ConstructorInfo [static_members.Length + instance_members.Length];
                static_members.CopyTo (all_members, 0); // copy all static members
                instance_members.CopyTo (all_members, static_members.Length); // copy all instance members

                return all_members;
        }
开发者ID:emtees,项目名称:old-code,代码行数:17,代码来源:updater.cs

示例9: GetConstructors

 public static ConstructorInfo[] GetConstructors(Type type, BindingFlags bindingAttr)
 {
     Requires.NotNull(type, "type");
     return type.GetConstructors(bindingAttr);
 }
开发者ID:johnhhm,项目名称:corefx,代码行数:5,代码来源:TypeExtensions.CoreCLR.cs

示例10: ParseTypeAccess

		private Expression ParseTypeAccess(Type type)
		{
			int errorPos = _token._pos;
			NextToken();
			if (_token._id == TokenId.Question)
			{
				if (!type.IsValueType || IsNullableType(type))
					throw ParseError(errorPos, Res.TypeHasNoNullableForm, GetTypeName(type));
				type = typeof (Nullable<>).MakeGenericType(type);
				NextToken();
			}
			if (_token._id == TokenId.OpenParen)
			{
				Expression[] args = ParseArgumentList();
				MethodBase method;
				switch (FindBestMethod(type.GetConstructors(), args, out method))
				{
					case 0:
						if (args.Length == 1)
							return GenerateConversion(args[0], type, errorPos);
						throw ParseError(errorPos, Res.NoMatchingConstructor, GetTypeName(type));
					case 1:
						return Expression.New((ConstructorInfo) method, args);
					default:
						throw ParseError(errorPos, Res.AmbiguousConstructorInvocation, GetTypeName(type));
				}
			}
			ValidateToken(TokenId.Dot, Res.DotOrOpenParenExpected);
			NextToken();
			return ParseMemberAccess(type, null);
		}
开发者ID:lakshithagit,项目名称:Target-Process-Plugins,代码行数:31,代码来源:Dynamic.cs

示例11: CreateNewInstance

  /*******************************/
  /// <summary>
  /// Creates an instance of a received Type.
  /// </summary>
  /// <param name="classType">The Type of the new class instance to return.</param>
  /// <returns>An Object containing the new instance.</returns>
  public static Object CreateNewInstance( Type classType )
  {
    Object instance = null;
    Type[] constructor = new Type[] { };
    ConstructorInfo[] constructors = null;

    constructors = classType.GetConstructors();

    if ( constructors.Length == 0 )
      throw new UnauthorizedAccessException();
    else
    {
      for ( int i = 0; i < constructors.Length; i++ )
      {
        ParameterInfo[] parameters = constructors[i].GetParameters();

        if ( parameters.Length == 0 )
        {
          instance = classType.GetConstructor( constructor ).Invoke( new Object[] { } );
          break;
        }
        else if ( i == constructors.Length - 1 )
          throw new MethodAccessException();
      }
    }
    return instance;
  }
开发者ID:Jaden-J,项目名称:csharp-sqlite,代码行数:33,代码来源:SupportClass.cs

示例12: GetConstructorsTest

	static void GetConstructorsTest (Type type, bool fromIL)
	{
		BindingFlags flags;
		ConstructorInfo [] ctors;

		flags = BindingFlags.Instance | BindingFlags.NonPublic;
		ctors = type.GetConstructors (flags);

		Assert.AreEqual (5, ctors.Length, "#A1");
		Assert.IsFalse (ctors [0].IsAssembly, "#A2:" + type.FullName);
		Assert.IsFalse (ctors [0].IsFamily, "#A3");
		Assert.IsFalse (ctors [0].IsFamilyAndAssembly, "#A4");
		Assert.IsFalse (ctors [0].IsFamilyOrAssembly, "#A5");
		Assert.IsTrue (ctors [0].IsPrivate, "#A6");
		Assert.IsFalse (ctors [0].IsPublic, "#A7");
		Assert.IsFalse (ctors [0].IsStatic, "#A8");
		Assert.IsFalse (ctors [1].IsAssembly, "#A9");
		Assert.IsTrue (ctors [1].IsFamily, "#A10");
		Assert.IsFalse (ctors [1].IsFamilyAndAssembly, "#A11");
		Assert.IsFalse (ctors [1].IsFamilyOrAssembly, "#A12");
		Assert.IsFalse (ctors [1].IsPrivate, "#A13");
		Assert.IsFalse (ctors [1].IsPublic, "#A14");
		Assert.IsFalse (ctors [1].IsStatic, "#A15");
		Assert.IsFalse (ctors [2].IsAssembly, "#A16");
		Assert.IsFalse (ctors [2].IsFamily, "#A17");
		if (fromIL) {
			Assert.IsTrue (ctors [2].IsFamilyAndAssembly, "#A18");
			Assert.IsFalse (ctors [2].IsFamilyOrAssembly, "#A19");
		} else {
			Assert.IsFalse (ctors [2].IsFamilyAndAssembly, "#A18");
			Assert.IsTrue (ctors [2].IsFamilyOrAssembly, "#A19");
		}
		Assert.IsFalse (ctors [2].IsPrivate, "#A20");
		Assert.IsFalse (ctors [2].IsPublic, "#A21");
		Assert.IsFalse (ctors [2].IsStatic, "#A22");
		Assert.IsFalse (ctors [3].IsAssembly, "#A23");
		Assert.IsFalse (ctors [3].IsFamily, "#A24");
		Assert.IsFalse (ctors [3].IsFamilyAndAssembly, "#A25");
		Assert.IsTrue (ctors [3].IsFamilyOrAssembly, "#A26");
		Assert.IsFalse (ctors [3].IsPrivate, "#A27");
		Assert.IsFalse (ctors [3].IsPublic, "#A28");
		Assert.IsFalse (ctors [3].IsStatic, "#A29");
		Assert.IsTrue (ctors [4].IsAssembly, "#A30");
		Assert.IsFalse (ctors [4].IsFamily, "#A31");
		Assert.IsFalse (ctors [4].IsFamilyAndAssembly, "#A32");
		Assert.IsFalse (ctors [4].IsFamilyOrAssembly, "#A33");
		Assert.IsFalse (ctors [4].IsPrivate, "#A34");
		Assert.IsFalse (ctors [4].IsPublic, "#A35");
		Assert.IsFalse (ctors [4].IsStatic, "#A36");

		flags = BindingFlags.Instance | BindingFlags.Public;
		ctors = type.GetConstructors (flags);

		Assert.AreEqual (1, ctors.Length, "#B1");
		Assert.IsFalse (ctors [0].IsAssembly, "#B2");
		Assert.IsFalse (ctors [0].IsFamily, "#B3");
		Assert.IsFalse (ctors [0].IsFamilyAndAssembly, "#B4");
		Assert.IsFalse (ctors [0].IsFamilyOrAssembly, "#B5");
		Assert.IsFalse (ctors [0].IsPrivate, "#B6");
		Assert.IsTrue (ctors [0].IsPublic, "#B7");
		Assert.IsFalse (ctors [0].IsStatic, "#B8");

		flags = BindingFlags.Static | BindingFlags.Public;
		ctors = type.GetConstructors (flags);

		Assert.AreEqual (0, ctors.Length, "#C1");

		flags = BindingFlags.Static | BindingFlags.NonPublic;
		ctors = type.GetConstructors (flags);

		Assert.AreEqual (1, ctors.Length, "#D1");
		Assert.IsFalse (ctors [0].IsAssembly, "#D2");
		Assert.IsFalse (ctors [0].IsFamily, "#D3");
		Assert.IsFalse (ctors [0].IsFamilyAndAssembly, "#D4");
		Assert.IsFalse (ctors [0].IsFamilyOrAssembly, "#D5");
		Assert.IsTrue (ctors [0].IsPrivate, "#D6");
		Assert.IsFalse (ctors [0].IsPublic, "#D7");
		Assert.IsTrue (ctors [0].IsStatic, "#D8");

		flags = BindingFlags.Instance | BindingFlags.NonPublic |
			BindingFlags.FlattenHierarchy;
		ctors = type.GetConstructors (flags);

		Assert.AreEqual (5, ctors.Length, "#E1");
		Assert.IsFalse (ctors [0].IsAssembly, "#E2");
		Assert.IsFalse (ctors [0].IsFamily, "#E3");
		Assert.IsFalse (ctors [0].IsFamilyAndAssembly, "#E4");
		Assert.IsFalse (ctors [0].IsFamilyOrAssembly, "#E5");
		Assert.IsTrue (ctors [0].IsPrivate, "#E6");
		Assert.IsFalse (ctors [0].IsPublic, "#E7");
		Assert.IsFalse (ctors [0].IsStatic, "#E8");
		Assert.IsFalse (ctors [1].IsAssembly, "#E9");
		Assert.IsTrue (ctors [1].IsFamily, "#E10");
		Assert.IsFalse (ctors [1].IsFamilyAndAssembly, "#E11");
		Assert.IsFalse (ctors [1].IsFamilyOrAssembly, "#E12");
		Assert.IsFalse (ctors [1].IsPrivate, "#E13");
		Assert.IsFalse (ctors [1].IsPublic, "#E14");
		Assert.IsFalse (ctors [1].IsStatic, "#E15");
		Assert.IsFalse (ctors [2].IsAssembly, "#E16");
		Assert.IsFalse (ctors [2].IsFamily, "#E17");
//.........这里部分代码省略.........
开发者ID:mono,项目名称:gert,代码行数:101,代码来源:test.cs

示例13: GenerateClass

    void GenerateClass(Type type)
    {
        output.Write ("\tpublic class " + type.GetTypeReferenceName () + " : ");
        string baseType = GetBaseTypeFromAttribute (type);
        if (baseType == null)
            output.WriteLine ("TypeScriptObject");
        else
            output.WriteLine (baseType);
        GenerateImplements (type);

        output.WriteLine ("\t{");

        output.WriteLine ("\t\tpublic {0} (ObjectInstance instance) : base (instance) {{}}", type.GetPrimaryName ());

        foreach (var c in type.GetConstructors (flags)) {
            if (!c.IsPublic)
                continue;

            // FIXME: they are workarounds for conflict betweeen
            // ctor(Object regex) and ctor(object instance)...
            if (type.GetTypeReferenceName () == "RegexLiteral" || type.GetTypeReferenceName () == "RegularExpressionLiteralToken")
                continue;

            output.WriteLine ("\t\tpublic {0} ({1})", type.GetPrimaryName (), GetArgumentsSignature (c));
            var args = GetMarshaledCallArguments (c);
            output.WriteLine ("\t\t\t : base (CallConstructor (\"{0}\", \"{1}\"{2}))", type.Namespace, type.GetTypeReferenceName (), args);
            output.WriteLine ("\t\t{");
            output.WriteLine ("\t\t}");
        }

        ImplementProperties (type);
        ImplementMethods (type);

        ImplementInterfaces (type);

        output.WriteLine ("\t}");
    }
开发者ID:atsushieno,项目名称:md-typescript,代码行数:37,代码来源:TS2CSImplementor.cs

示例14: ResolveAttributeConstructor

        protected static ConstructorInfo ResolveAttributeConstructor(Type attributeType, Type[] parameterTypes)
        {
            int parameterCount = parameterTypes.Length;
            foreach (ConstructorInfo candidate in attributeType.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly))
            {
                ParameterInfo[] candidateParameters = candidate.GetParametersNoCopy();
                if (parameterCount != candidateParameters.Length)
                    continue;

                for (int i = 0; i < parameterCount; i++)
                {
                    if (!parameterTypes[i].Equals(candidateParameters[i]))
                        continue;
                }

                return candidate;
            }

            throw new MissingMethodException();
        }
开发者ID:krytarowski,项目名称:corert,代码行数:20,代码来源:RuntimeCustomAttributeData.cs

示例15: GetDeserializationConstructor

        internal static ConstructorInfo GetDeserializationConstructor(Type t)
        {
            // TODO #10530: Use Type.GetConstructor that takes BindingFlags when it's available
            foreach (ConstructorInfo ci in t.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly))
            {
                ParameterInfo[] parameters = ci.GetParameters();
                if (parameters.Length == 2 &&
                    parameters[0].ParameterType == typeof(SerializationInfo) &&
                    parameters[1].ParameterType == typeof(StreamingContext))
                {
                    return ci;
                }
            }

            throw new SerializationException(SR.Format(SR.Serialization_ConstructorNotFound, t.FullName));
        }
开发者ID:dotnet,项目名称:corefx,代码行数:16,代码来源:ObjectManager.cs


注:本文中的Type.GetConstructors方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。