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


C# Assembly.First方法代码示例

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


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

示例1: Amend

		/// <summary>
		/// Amends the specified target assembly, optionally using assembly amendments defined in the 
		/// specified amendment assemblies.
		/// </summary>
		/// <param name="targetAssembly"></param>
		/// <param name="amendmentAssemblies"></param>
		internal static void Amend(string targetAssembly, string[] amendmentAssemblies, string[] referenceAssemblies)
		{
			// Verify the target assembly exists
			targetAssembly = Path.GetFullPath(targetAssembly);
			if (!File.Exists(targetAssembly))
				throw new ArgumentException("The specified target assembly, " + targetAssembly + ", does not exist.");

			// Verify the amendment assemblies exist
			if (amendmentAssemblies == null)
				amendmentAssemblies = new string[0];
			for (int i = 0; i < amendmentAssemblies.Length; i++)
			{
				var path = amendmentAssemblies[i] = Path.GetFullPath(amendmentAssemblies[i]);
				if (!File.Exists(path))
					throw new ArgumentException("The specified amendment assembly, " + path + ", does not exist.");
			}

			// Verify that the target has not already been amended
			var afterthoughtTracker = targetAssembly + ".afterthought";
			if (File.Exists(afterthoughtTracker) && File.GetLastWriteTime(targetAssembly) == File.GetLastWriteTime(afterthoughtTracker))
				return;

			// Determine the set of target directories and backup locations
			var targetWriteTime = File.GetLastWriteTime(targetAssembly);
			var backupTargetAssembly = targetAssembly + ".backup";
			var targetDirectory = Path.GetDirectoryName(targetAssembly);
			File.Delete(backupTargetAssembly);
			File.Move(targetAssembly, backupTargetAssembly);

			// Build up a set of paths with resolving assemblies
			var referencePaths = new Dictionary<string, string>();
			foreach (string path in amendmentAssemblies
				.Union(referenceAssemblies)
				.Union(Directory.GetFiles(targetDirectory).Where(p => p.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) && p != targetAssembly)))
				referencePaths[Path.GetFileName(path)] = path;

			// Register an assembly resolver to look in assembly directories when resolving assemblies
			AppDomain.CurrentDomain.AssemblyResolve += (s, e) =>
			{
				var assemblyName = new System.Reflection.AssemblyName(e.Name).Name + ".dll";
				string referencePath;
				if (referencePaths.TryGetValue(assemblyName, out referencePath))
					return System.Reflection.Assembly.LoadFrom(referencePath);

				return null;
			};

			// Get the set of amendments to apply from all of the specified assemblies
			var assemblies = new System.Reflection.Assembly[] { System.Reflection.Assembly.LoadFrom(backupTargetAssembly) }.Union(amendmentAssemblies.Select(a => System.Reflection.Assembly.LoadFrom(a)));
			var amendments = AmendmentAttribute.GetAmendments(assemblies.First(), assemblies.Skip(1).ToArray()).ToList();

			// Exit immediately if there are no amendments in the target assemblies
			if (amendments.Count == 0)
			    return;

			// Amend the target assembly
			Console.Write("Amending " + Path.GetFileName(targetAssembly));
			var start = DateTime.Now;

			using (var host = new PeReader.DefaultHost())
			{
				foreach (var referencePath in referencePaths.Select(p => Path.GetDirectoryName(p.Value)).Distinct())
					host.AddLibPath(referencePath);

				// Load the target assembly
				IModule module = host.LoadUnitFrom(backupTargetAssembly) as IModule;
				if (module == null || module == Dummy.Module || module == Dummy.Assembly)
					throw new ArgumentException(backupTargetAssembly + " is not a PE file containing a CLR assembly, or an error occurred when loading it.");

				// Copy the assembly to enable it to be mutated
				module = new MetadataDeepCopier(host).Copy(module);

				// Load the debug file if it exists
				PdbReader pdbReader = null;
				var pdbFile = Path.Combine(targetDirectory, Path.GetFileNameWithoutExtension(targetAssembly) + ".pdb");
				var backupPdbFile = pdbFile + ".backup";
				if (File.Exists(pdbFile))
				{
					File.Delete(backupPdbFile);
					File.Move(pdbFile, backupPdbFile);
					using (var pdbStream = File.OpenRead(backupPdbFile))
					{
						pdbReader = new PdbReader(pdbStream, host);
					}
				}
					
				// Amend and persist the target assembly
				using (pdbReader)
				{
					// Create and execute a new assembly amender
					AssemblyAmender amender = new AssemblyAmender(host, pdbReader, amendments, assemblies);
					amender.TargetRuntimeVersion = module.TargetRuntimeVersion;
					module = amender.Visit(module);

//.........这里部分代码省略.........
开发者ID:Biegal,项目名称:Afterthought,代码行数:101,代码来源:Program.cs

示例2: InvokeSafelyForForms

        /// <summary>
        /// Invokes the method on the first form if need be
        /// </summary>
        /// <param name="EvalMethod"></param>
        /// <returns>The result of the safe call to EvalMethod</returns>
        /// <remarks>
        /// As we dont want to require the forms assembly for debugutils to work, we need to do all 
        /// our calling of Forms functions via reflection. The method handles all that but in return is a ugly, ugly
        /// piece of code. We basically do the following snippet but with reflection:
        /// 
        /// if(Application.OpenForms.Count > 0)
        /// {
        ///     if(Application.OpenForms[0].InvokeRequired)
        ///     {
        ///         return Application.OpenForms[0].Invoke(new Func<object>(() => 
        ///             Invoke(evalMethod)), new object[] { });
        ///     }
        /// }
        /// return EvalMethod.Invoke(null, new object[] { });
        /// 
        /// </remarks>
        private object InvokeSafelyForForms(Assembly[] assemblies, MethodInfo evalMethod)
        {
            //obtain a reference to the forms assembly 
            Assembly formsAssembly = assemblies.First(a => a.GetName().Name == "System.Windows.Forms");

            //obtain a reference to the application type
            Type applicationType = formsAssembly.GetType("System.Windows.Forms.Application");

            //next, look for the openForms Property and get its value
            PropertyInfo openFormsPropertyInfo = applicationType.GetProperty("OpenForms");
            object openForms = openFormsPropertyInfo.GetValue(null, null);

            //We now have a reference to our FormCollection. Next we need to see if it has elements. 
            //The get_Count method does this for us
            MethodInfo countMethod = openForms.GetType().GetMethod("get_Count");
            //actually invoke the method and cast to int
            int formCount = (int)countMethod.Invoke(openForms, null);

            // at this point we basically did 
            // int formCount = Application.OpenForms.Count
            // but with reflection. Next we need to check if there even are any forms.

            if (formCount > 0)
            {
                //as we found forms, we now need a reference to a specific one. 
                //For now we will always use the first form in the list, as your typical Windows Forms Application
                //creates all Forms on the same thread anyways
                object openForm = openForms.GetType().GetMethod("get_Item", new Type[] { typeof(int) })
                    .Invoke(openForms, new object[] { 0 });

                //next get the invoke required property, to see if we need to proxy our call
                bool invokeRequired = (bool)openForm.GetType().GetProperty("InvokeRequired").GetValue(openForm, null);

                if (invokeRequired)
                {
                    //get the invoke method of the form so we can proxy our call to it
                    MethodInfo invokeMethod = openForm.GetType().GetMethod("Invoke", new Type[] { typeof(Delegate) });
                    //create an appropriate delegate
                    Delegate proxy = new Func<object>(() => InvokeUnsafe(evalMethod));
                    //finally invoke the proxy on the form and return the value
                    return invokeMethod.Invoke(openForm, new object[] { proxy });
                }
            }

            //we dont need to proxy the call so we can just invoke our method
            return InvokeUnsafe(evalMethod);
        }
开发者ID:lameox,项目名称:DebugUtilsV2,代码行数:68,代码来源:CodeExecutionRequest.cs


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