返回首页

简介
本文将重点。NET Framework中的反射API。反思文档通常包括属性和编写动态代码,但我会避免后者,并试图解释一些比较重要的方面使用反射,即使它可能不会出现有任何书面现实世界的应用价值。相反,它和一个人得到精通它,将能够使用反射写开发工具,甚至计划,减少堆消费。对于初学者的重要缘故,某些路段会一步虽然一些源代码,以获得一个C#语法的掌握,但在我有限的知识)的文章(大概接近中间。反射是经常被用来确定哪些类型的程序集的定义。 Framework类库提供了许多方法来获取这些信息,但最常用的方法是大会GetExportedTypes。以下只是一些示例源代码,加载程序集和显示中定义的所有公开导出的类型名称。一些基本的解释后,输出会出现在下面的部分。检查此代码,然后我们将在大会类的方法,属性和静态方法。 大会类的静态方法GetAssemblyGetCallingAssemblyGetEntryAssemblyGetExecutingAssembly负载的LoadFile的LoadFromReflectionOnlyLoadReflectionOnlyLoadFrom
正如你可以看到,GetExportedTypes方法也不是一成不变的的。检查大会类的属性:入口点真实姓名GlobalAssemblyCache地点ReflectionOnly
在这一点上,它是重要的检查语法。研究这个程序:{C}
下面是输出:

c:\Windows\Microsoft.NET\Framework\v4.0.30319>getmod

System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

From GAC? True

Path:     C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System\v4.0_4.0.0.0__b77a5c

561934e089\System.dll

Version:  v4.0.30319

   Mod: System.dll



GetMod, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null

From GAC? False

Path:     c:\Windows\Microsoft.NET\Framework\v4.0.30319\GetMod.exe

Version:  v4.0.30319

   Mod: GetMod.exe     

代码首先声明了一个字符串:
string path = @"C:\windows\Microsoft.net\Framework\v2.0.50727\System.dll";

引号的字符串存储在分配给String对象的值??代码>路径??因此认为在左引号中(其中包含要加载的程序集)的目录路径的参考。下一行代码实例化类大会。这是等于向大会类??静态方法的LoadFile。请注意,该方法具有上述路径(其中存储的字符串值)作为参数传递的值。还要注意以下代码>大会现在存储该程序集的路径,因为它现在已经加载????:
Assembly a = Assembly.LoadFile(path); 

在这一点上,我们写了一个静态方法来显示当前加载的程序集的信息。目前正在执行中,我们实例大会类的另一个实例。静态方法ShowAssemblyInfo做什么顾名思义。重要的是对于初学者要注意原始值的代码>一个是作为参数传递的是点语法写入显示属性的字符串路径的参考作用:???(一个地点,a.GlobalAssemblyCache,a.FullName,等等)下面是一些大会类的方法,AREN,AOT静态??:的CreateInstanceGetCustomAttributesGetExportedTypesGetModuleGetModulesGetTypes
在说,让AOS看看原始的源代码的输出。对于为了简单起见,请注意,这些都是(近一半)市民的出口类型:
System.Text.RegularExpressions.Regex

System.Text.RegularExpressions.MatchEvaluator

System.Text.RegularExpressions.Capture

System.Text.RegularExpressions.CaptureCollection

System.Text.RegularExpressions.RegexCompilationInfo

System.Text.RegularExpressions.Group

System.Text.RegularExpressions.GroupCollection

System.Text.RegularExpressions.RegexRunner

System.Text.RegularExpressions.Match

System.Text.RegularExpressions.MatchCollection

System.Text.RegularExpressions.RegexOptions

System.Text.RegularExpressions.RegexRunnerFactory

System.CodeDom.CodeObject

System.CodeDom.CodeExpression

System.CodeDom.CodeArgumentReferenceExpression

System.CodeDom.CodeArrayCreateExpression

System.CodeDom.CodeArrayIndexerExpression

System.CodeDom.CodeStatement

System.CodeDom.CodeAssignStatement

System.CodeDom.CodeAttachEventStatement

System.CodeDom.CodeAttributeArgument

System.CodeDom.CodeAttributeArgumentCollection

System.CodeDom.CodeAttributeDeclaration

System.CodeDom.CodeAttributeDeclarationCollection

System.CodeDom.CodeBaseReferenceExpression

System.CodeDom.CodeBinaryOperatorExpression

System.CodeDom.CodeBinaryOperatorType

System.CodeDom.CodeCastExpression

System.CodeDom.CodeCatchClause

System.CodeDom.CodeCatchClauseCollection

System.CodeDom.CodeDirective

System.CodeDom.CodeChecksumPragma

System.CodeDom.CodeComment

System.CodeDom.CodeCommentStatement

System.CodeDom.CodeCommentStatementCollection

System.CodeDom.CodeCompileUnit

System.CodeDom.CodeConditionStatement

System.CodeDom.CodeTypeMember

System.CodeDom.CodeMemberMethod

System.CodeDom.CodeConstructor

System.CodeDom.CodeDefaultValueExpression

System.CodeDom.CodeDelegateCreateExpression

System.CodeDom.CodeDelegateInvokeExpression

System.CodeDom.CodeDirectionExpression

System.CodeDom.CodeDirectiveCollection

System.CodeDom.CodeEntryPointMethod

System.CodeDom.CodeEventReferenceExpression

System.CodeDom.CodeExpressionCollection

System.CodeDom.CodeExpressionStatement

System.CodeDom.CodeFieldReferenceExpression

System.CodeDom.CodeGotoStatement

System.CodeDom.CodeIndexerExpression

System.CodeDom.CodeIterationStatement

System.CodeDom.CodeLabeledStatement

System.CodeDom.CodeLinePragma

System.CodeDom.CodeMemberEvent

System.CodeDom.CodeMemberField

System.Net.FileWebResponse

System.Net.FtpStatusCode

?etc ?
System.Net.NetworkInformation.NetworkInterface

System.Net.NetworkInformation.NetworkInterfaceComponent

System.Net.NetworkInformation.NetBiosNodeType

System.Net.NetworkInformation.OperationalStatus

System.Net.NetworkInformation.PhysicalAddress

System.Net.NetworkInformation.PingCompletedEventHandler

System.Net.NetworkInformation.PingCompletedEventArgs

System.Net.NetworkInformation.Ping

System.Net.NetworkInformation.PingException

System.Net.NetworkInformation.PingOptions

System.Net.NetworkInformation.PingReply

System.Net.NetworkInformation.PrefixOrigin

System.Net.NetworkInformation.SuffixOrigin

System.Net.NetworkInformation.TcpConnectionInformation

System.Net.NetworkInformation.TcpStatistics

System.Net.NetworkInformation.UdpStatistics

System.Net.NetworkInformation.TcpState

System.Net.Configuration.AuthenticationModuleElement

System.Net.Configuration.AuthenticationModuleElementCollection

System.Net.Configuration.AuthenticationModulesSection

System.Net.Configuration.BypassElement

System.Net.Configuration.BypassElementCollection

System.Net.Configuration.ConnectionManagementElement

System.Net.Configuration.ConnectionManagementElementCollection

System.Net.Configuration.ConnectionManagementSection

System.Net.Configuration.DefaultProxySection

System.Net.Configuration.HttpWebRequestElement

System.Net.Configuration.HttpListenerElement

System.Net.Configuration.HttpCachePolicyElement

System.Net.Configuration.FtpCachePolicyElement

System.Net.Configuration.Ipv6Element

System.Net.Configuration.MailSettingsSectionGroup

System.Net.Configuration.ModuleElement

System.Net.Configuration.NetSectionGroup

System.Net.Configuration.PerformanceCountersElement

System.Net.Configuration.ProxyElement

System.Net.Configuration.ProxyElement+BypassOnLocalValues

System.Net.Configuration.ProxyElement+UseSystemDefaultValues

System.Net.Configuration.ProxyElement+AutoDetectValues

System.Net.Configuration.RequestCachingSection

System.Configuration.SchemeSettingElement

System.Configuration.SchemeSettingElementCollection

System.Net.Configuration.SettingsSection

System.Net.Configuration.ServicePointManagerElement

System.Net.Configuration.SmtpSection

System.Net.Configuration.SmtpNetworkElement

System.Net.Configuration.SmtpSpecifiedPickupDirectoryElement

System.Net.Configuration.SocketElement

?.etc?

System.Diagnostics.FileVersionInfo

System.Diagnostics.ICollectData

System.Diagnostics.InstanceData

System.Diagnostics.InstanceDataCollection

System.Diagnostics.InstanceDataCollectionCollection

System.Diagnostics.MonitoringDescriptionAttribute

System.Diagnostics.OverflowAction

System.Diagnostics.PerformanceCounter

System.Diagnostics.PerformanceCounterCategory

System.Diagnostics.PerformanceCounterCategoryType

System.Diagnostics.PerformanceCounterInstanceLifetime

System.Diagnostics.PerformanceCounterManager

System.Diagnostics.PerformanceCounterPermission

System.Diagnostics.PerformanceCounterPermissionAccess

System.Diagnostics.PerformanceCounterPermissionAttribute

System.Diagnostics.PerformanceCounterPermissionEntry

System.Diagnostics.PerformanceCounterPermissionEntryCollection

System.Diagnostics.PerformanceCounterType

System.Diagnostics.Process

System.Diagnostics.ProcessModule

System.Diagnostics.ProcessModuleCollection

System.Diagnostics.ProcessPriorityClass

System.Diagnostics.ProcessStartInfo

System.Diagnostics.ProcessThread

System.Diagnostics.ProcessThreadCollection

System.Diagnostics.ProcessWindowStyle

System.Diagnostics.Stopwatch

System.Diagnostics.ThreadPriorityLevel

System.Diagnostics.ThreadState

System.Diagnostics.ThreadWaitReason

System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute

System.Configuration.AppSettingsReader

System.IO.Ports.Handshake

System.IO.Ports.Parity

System.IO.Ports.SerialError

System.IO.Ports.SerialErrorReceivedEventArgs

System.IO.Ports.SerialErrorReceivedEventHandler

System.IO.Ports.SerialPinChange

System.IO.Ports.SerialPinChangedEventArgs

System.IO.Ports.SerialPinChangedEventHandler

System.IO.Ports.SerialPort

System.IO.Ports.SerialData

System.IO.Ports.SerialDataReceivedEventArgs

System.IO.Ports.SerialDataReceivedEventHandler

System.IO.Ports.StopBits   
该对象是什么类型?
或者,什么是类型对象呢?正如我们都知道,。NET中的所有对象派生自System.Object。在这根命名空间中定义的方法的GetType。请注意,前面的代码迭代的System.Type对象数组。的System.Type类型是你的出发点做类型和对象操作。的System.Type是一个抽象基的类型从System.Reflection.MemberInfo派生(因为类型可以是另一种类型的成员)。整箱提供了几种类型的System.Type从派生:System.RuntimeType, System.ReflectionOnlyType,System.Reflection.TypeDelegator,并在System.Reflection中定义的一些类型。发出的命名空间(EnumBuilder,GenericTypeParameterBuilder,并TypeBuilder)。 Object类支持的方法GetType返回一个类型的对象,是指一个对象的实际类型。例如,让AOS创建一个动物类,然后创建两个类,动物类派生:
using System;

public class Animal

   {

   }

public class Dog : Animal

   {

   }

public class Cat : Animal

   {

   }

class App {

static void Main() {

Animal aAnim = new Animal();

Animal aDog = new Dog();

Animal aCat = new Cat();

Console.WriteLine("Typename for aAnim is {0}", aAnim.GetType().Name);

Console.WriteLine("Typename for aDog is {0}", aDog.GetType().Name);

Console.WriteLine("Typename for aCat is  {0}", aCat.GetType().Name);

 }

}   

输出与预期。请注意使用的代码> typeof关键字???:
Typename for aAnim is Animal

Typename for aDog   is Dog

Typename for aCat   is  Cat  

构造泛型类型的实例,首先获得一个开放式的参考,然后呼叫类型,AOS公共实例调用MakeGenericType方法,传递要使用类型参数类型的数组。然后,返回的类型对象,并传递到上面列出的各种方法之一。下面是一个例子:
using System; 

using System.Reflection; 

using System.Collections.Generic; 

using System.Linq; 

internal sealed class Dictionary<tkey, /> { } 

public static class Program { 

public static void Main() 

{ 

Type openType = typeof(Dictionary<,>); 

Type closedType = openType.MakeGenericType(typeof(String), 

	typeof(Int32)); Object o = Activator.CreateInstance(closedType); 

Console.WriteLine(o.GetType()); 

} 

}  

当您编译此代码,你应该得到以下结果:
Dictionary`2[System.String,System.Int32]    
使用反射来发现一个类型的成员
据微软的技术文档,能够发现和调用类型的成员通常用于创建开发工具和实用程序,通过一定的编程模式,或使用某些成员大会,分析。工具/实用工具,做到这一点的例子是ILDASM.EXE,FxCopCmd.exe,和Visual Studio中的Windows窗体和网页设计师。
字段,构造,方法,属性,事件,和嵌套类型都可以被定义为在一个类型的成员。整箱包含名为System.Reflection.MemberInfo类型。这个类是一个抽象的基类,它封装了所有类型的成员的共同属性的一堆。从MemberInfo的派生一堆类,每类封装了相关的一些特定类型的成员更多的属性。以下是这些类型的层次结构列表:
System.Object

System.Reflection.MemberInfo

System.Type

System.Reflection.FieldInfo

System.Reflection.MethodBase

System.Reflection.ContructorInfo

System.Reflection.MethodInfo

System.Reflection.PropertyInfo

System.Reflection.EventInfo    

对于每个类型的,GetMembers方法被调用,并返回的MemberInfo派生的对象的数组,每个对象是指一个单一的类型内定义的成员。 ,BF的BindingFlags变量传递到GetMembers方法,告诉该方法返回成员。然后,为每个成员,其种类(字段,构造函数,方法,属性,等)和它的字符串值(调用toString得到)所示。不久将讨论主题的BindingFlags。研究这样的代码:
using System;

using System.Reflection;

public static class Program {

public static void Main() {

// Loop through all assemblies loaded in this AppDomain

Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();

foreach (Assembly a in assemblies) {

WriteLine(0, "Assembly: {0}", a);

// Find Types in the assembly

foreach (Type t in a.GetExportedTypes()) {

WriteLine(1, "Type: {0}", t);

// Discover the type's members

const BindingFlags bf = BindingFlags.DeclaredOnly |

BindingFlags.NonPublic | BindingFlags.Public |

BindingFlags.Instance | BindingFlags.Static;

foreach (MemberInfo mi in t.GetMembers(bf)) {

String typeName = String.Empty;

if (mi is Type) typeName = "(Nested) Type";

else if (mi is FieldInfo) typeName = "FieldInfo";

else if (mi is MethodInfo) typeName = "MethodInfo";

else if (mi is ConstructorInfo) typeName = "ConstructoInfo";

else if (mi is PropertyInfo) typeName = "PropertyInfo";

else if (mi is EventInfo) typeName = "EventInfo";

WriteLine(2, "{0}: {1}", typeName, mi);

    }

  }

 }

}

 private static void WriteLine(Int32 indent, String format, params Object[] args) {

Console.WriteLine(new String(' ', 3 * indent) + format, args);

  }

}

编译后的代码运行时,大量的信息输出。这里是一个小样本的输出,并尝试建立连接的层次结构列表。
Assembly: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

   Type: System.Object

      MethodInfo: System.String ToString()

      MethodInfo: Boolean Equals(System.Object)

      MethodInfo: Boolean Equals(System.Object, System.Object)

      MethodInfo: Boolean ReferenceEquals(System.Object, System.Object)

      MethodInfo: Int32 GetHashCode()

      MethodInfo: System.Type GetType()

      MethodInfo: Void Finalize()

      MethodInfo: System.Object MemberwiseClone()

      MethodInfo: Void FieldSetter(System.String, System.String, System.Object)

      MethodInfo: Void FieldGetter(System.String, System.String, System.Object ByRef)

      MethodInfo: System.Reflection.FieldInfo GetFieldInfo(System.String, System.String)

      ConstructoInfo: Void .ctor()

   Type: System.Runtime.Serialization.ISerializable

      MethodInfo: Void GetObjectData(System.Runtime.Serialization.SerializationInfo, 

	System.Runtime.Serialization.StreamingContext)

   Type: System.Runtime.InteropServices._Exception

      MethodInfo: System.String ToString()

      MethodInfo: Boolean Equals(System.Object)

      MethodInfo: Int32 GetHashCode()

      MethodInfo: System.Type GetType()

      MethodInfo: System.String get_Message()

      MethodInfo: System.Exception GetBaseException()

      MethodInfo: System.String get_StackTrace()

      MethodInfo: System.String get_HelpLink()

      MethodInfo: Void set_HelpLink(System.String)

      MethodInfo: System.String get_Source()

      MethodInfo: Void set_Source(System.String)

      MethodInfo: Void GetObjectData(System.Runtime.Serialization.SerializationInfo, 

	System.Runtime.Serialization.StreamingContext)

      MethodInfo: System.Exception get_InnerException()

      MethodInfo: System.Reflection.MethodBase get_TargetSite()

      PropertyInfo: System.String Message

      PropertyInfo: System.String StackTrace

      PropertyInfo: System.String HelpLink

      PropertyInfo: System.String Source

      PropertyInfo: System.Exception InnerException

      PropertyInfo: System.Reflection.MethodBase TargetSite

   Type: System.Exception

      MethodInfo: System.String get_Message()

      MethodInfo: System.Collections.IDictionary get_Data()

      MethodInfo: System.Exception GetBaseException()

      MethodInfo: System.Exception get_InnerException()

      MethodInfo: System.Reflection.MethodBase get_TargetSite()

      MethodInfo: System.Reflection.MethodBase GetTargetSiteInternal()

      MethodInfo: System.String get_StackTrace()

      MethodInfo: System.String GetStackTrace(Boolean)

      MethodInfo: Void SetErrorCode(Int32)

      MethodInfo: System.String get_HelpLink()

      MethodInfo: Void set_HelpLink(System.String)

      MethodInfo: System.String get_Source()

      MethodInfo: Void set_Source(System.String)

      MethodInfo: System.String ToString()

      MethodInfo: System.String ToString(Boolean)

      MethodInfo: Void add_SerializeObjectState

	(System.EventHandler`1[System.Runtime.Serialization.SafeSerializationEventArgs])

      MethodInfo: Void remove_SerializeObjectState

	(System.EventHandler`1[System.Runtime.Serialization.SafeSerializationEventArgs])

      MethodInfo: Void GetObjectData

	(System.Runtime.Serialization.SerializationInfo, 

	System.Runtime.Serialization.StreamingContext)

      MethodInfo: System.Exception PrepForRemoting()

      MethodInfo: Void InternalPreserveStackTrace()

      MethodInfo: Int32 get_HResult()

      MethodInfo: Void set_HResult(Int32)

      MethodInfo: System.String InternalToString()

      MethodInfo: System.Type GetType()

      MethodInfo: Boolean get_IsTransient()

      MethodInfo: System.String GetMessageFromNativeResources(ExceptionMessageKind)

      MethodInfo: Void Init()

      MethodInfo: Boolean IsImmutableAgileException(System.Exception)

      MethodInfo: System.String GetClassName()

      MethodInfo: System.IRuntimeMethodInfo GetMethodFromStackTrace(System.Object)

      MethodInfo: System.Reflection.MethodBase GetExceptionMethodFromStackTrace()

      MethodInfo: System.String GetExceptionMethodString()

      MethodInfo: System.Reflection.MethodBase GetExceptionMethodFromString()

      MethodInfo: Void OnDeserialized(System.Runtime.Serialization.StreamingContext)

      MethodInfo: Boolean nIsTransient(Int32)

      MethodInfo: Void GetMessageFromNativeResources

	(ExceptionMessageKind, System.Runtime.CompilerServices.StringHandleOnStack)

      ConstructoInfo: Void .ctor()

      ConstructoInfo: Void .ctor(System.String)

      ConstructoInfo: Void .ctor(System.String, System.Exception)

      ConstructoInfo: Void .ctor

	(System.Runtime.Serialization.SerializationInfo, 

	System.Runtime.Serialization.StreamingContext)

      PropertyInfo: System.String Message

      PropertyInfo: System.Collections.IDictionary Data

      PropertyInfo: System.Exception InnerException

      PropertyInfo: System.Reflection.MethodBase TargetSite

      PropertyInfo: System.String StackTrace

      PropertyInfo: System.String HelpLink

      PropertyInfo: System.String Source

      PropertyInfo: Int32 HResult

      PropertyInfo: Boolean IsTransient

      EventInfo: System.EventHandler`1

	[System.Runtime.Serialization.SafeSerializationEventArgs] SerializeObjectState

      FieldInfo: System.String _className

      FieldInfo: System.Reflection.MethodBase _exceptionMethod

      FieldInfo: System.String _exceptionMethodString

      FieldInfo: System.String _message

      FieldInfo: System.Collections.IDictionary _data

      FieldInfo: System.Exception _innerException

      FieldInfo: System.String _helpURL

      FieldInfo: System.Object _stackTrace

      FieldInfo: System.Object _watsonBuckets

      FieldInfo: System.String _stackTraceString

      FieldInfo: System.String _remoteStackTraceString

      FieldInfo: Int32 _remoteStackIndex

      FieldInfo: System.Object _dynamicMethods

      FieldInfo: Int32 _HResult

      FieldInfo: System.String _source

      FieldInfo: IntPtr _xptrs

      FieldInfo: Int32 _xcode

      FieldInfo: UIntPtr _ipForWatsonBuckets

      FieldInfo: System.Runtime.Serialization.SafeSerializationManager 

		_safeSerializationManager

      FieldInfo: Int32 _COMPlusExceptionCode

      (Nested) Type: System.Exception+ExceptionMessageKind

   Type: System.ValueType

      MethodInfo: Boolean Equals(System.Object)

      MethodInfo: Int32 GetHashCode()

      MethodInfo: Int32 GetHashCodeOfPtr(IntPtr)

      MethodInfo: System.String ToString()

      MethodInfo: Boolean CanCompareBits(System.Object)

      MethodInfo: Boolean FastEqualsCheck(System.Object, System.Object)

      ConstructoInfo: Void .ctor()       
使用的的BindingFlags
BindingFlags枚举是用来控制一个类型的成员是如何检索使用的GetMembers方法,以及每个成员的类型的具体成员。更重要的一点,选举产生的议员的BindingFlags筛选种。您查询的类型,调用类型,AOS GetMembers,GetNestedTypes,GetFields,GetConstructors,GetMethods,GetProperties,或GetEvents方法AOS成员。当您调用这些方法中的任何一种,您可以通过在一个System.Reflection.BindingFlags枚举类型的一个实例。枚举类型的标识设置标志位,AOD一起帮助您过滤,这些方法返回的成员。尽管事实是,我们使用的BindingFlags是我们最后一个例子,这里是源代码,充分体现了其直目的:
using System;

using System.Reflection;

public class Program

 {

    public static void Main(string[]  args)

    {

      string path = @"C:\Windows\Microsoft.NET\Framework\v2.0.50727\" +

      "System.ServiceProcess.dll";



       // using BindingFlags to only get the declared

       // and instance members



       BindingFlags flags =

       BindingFlags.DeclaredOnly |

       BindingFlags.Public |

       BindingFlags.Instance;



       Assembly a = Assembly.LoadFrom(path);

       Console.WriteLine(a.FullName);



       Type[] types = a.GetTypes();



       foreach ( Type t in types )

       {

         Console.WriteLine("  Type:  {0}", t.Name);

         MemberInfo[] m = t.GetMembers(flags);



       foreach (MemberInfo member in m)

        {

           Console.WriteLine("  {0}: {1}", member.MemberType, member.Name);

        }

       }



       Console.Read();

     }

  }  

当我们运行编译后的代码,我们将看到(像往常一样,有大量信息),净使用API​​返回信息类型thatnbsp;接受的BindingFlags标志风格的枚举值来约束搜索那些持有的某些属性的抽象:
System.ServiceProcess, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a

  Type:  NativeMethods

  NestedType: SERVICE_STATUS

  NestedType: ServiceMainCallback

  NestedType: ServiceControlCallback

  NestedType: ServiceControlCallbackEx

  NestedType: StructFormat

  NestedType: ENUM_SERVICE_STATUS

  NestedType: ENUM_SERVICE_STATUS_PROCESS

  NestedType: QUERY_SERVICE_CONFIG

  NestedType: SERVICE_TABLE_ENTRY

  NestedType: LSA_UNICODE_STRING

  NestedType: LSA_UNICODE_STRING_withPointer

  NestedType: LSA_OBJECT_ATTRIBUTES

  NestedType: SERVICE_DESCRIPTION

  NestedType: SERVICE_DELAYED_AUTOSTART_INFO

  NestedType: SERVICE_FAILURE_ACTIONS

  NestedType: SC_ACTION

  NestedType: WTSSESSION_NOTIFICATION

  Type:  SERVICE_STATUS

  Field: serviceType

  Field: currentState

  Field: controlsAccepted

  Field: win32ExitCode

  Field: serviceSpecificExitCode

  Field: checkPoint

  Field: waitHint

  Type:  ServiceMainCallback

  Method: Invoke

  Method: BeginInvoke

  Method: EndInvoke

  Constructor: .ctor

  Type:  ServiceControlCallback

  Method: Invoke

  Method: BeginInvoke

  Method: EndInvoke

  Constructor: .ctor

  Type:  ServiceControlCallbackEx

  Method: Invoke

  Method: BeginInvoke

  Method: EndInvoke

  Constructor: .ctor

  Type:  PowerBroadcastStatus

  Field: value__

  Type:  SafeNativeMethods

  Type:  ServiceAccount

  Field: value__

  Type:  ServiceBase

  Method: RequestAdditionalTime

  Method: get_AutoLog

  Method: set_AutoLog

  Method: get_ExitCode

  Method: set_ExitCode

  Method: get_CanHandlePowerEvent

  Method: set_CanHandlePowerEvent

  Method: get_CanHandleSessionChangeEvent

  Method: set_CanHandleSessionChangeEvent

  Method: get_CanPauseAndContinue

  Method: set_CanPauseAndContinue

  Method: get_CanShutdown

  Method: set_CanShutdown

  Method: get_CanStop

  Method: set_CanStop

  Method: get_EventLog

  Method: get_ServiceName

  Method: set_ServiceName

  Method: Stop

  Method: ServiceMainCallback

  Constructor: .ctor

  Property: AutoLog

  Property: ExitCode

  Property: CanHandlePowerEvent

  Property: CanHandleSessionChangeEvent

  Property: CanPauseAndContinue

  Property: CanShutdown

  Property: CanStop

  Property: EventLog

  Property: ServiceName

  Type:  ServiceController

  Method: get_CanPauseAndContinue

  Method: get_CanShutdown

  Method: get_CanStop

  Method: get_DisplayName

  Method: set_DisplayName

  Method: get_DependentServices

  Method: get_MachineName

  Method: set_MachineName

  Method: get_ServiceName

  Method: set_ServiceName

  Method: get_ServicesDependedOn

  Method: get_ServiceHandle

  Method: get_Status

  Method: get_ServiceType

  Method: Close

  Method: Pause

  Method: Continue

  Method: ExecuteCommand

  Method: Refresh

  Method: Start

  Method: Start

  Method: Stop

  Method: WaitForStatus

  Method: WaitForStatus

  Constructor: .ctor

  Constructor: .ctor

  Constructor: .ctor

  Property: CanPauseAndContinue

  Property: CanShutdown

  Property: CanStop

  Property: DisplayName

  Property: DependentServices

  Property: MachineName

  Property: ServiceName

  Property: ServicesDependedOn

  Property: ServiceHandle

  Property: Status

  Property: ServiceType

  Type:  ServiceControllerPermission

  Method: get_PermissionEntries

  Constructor: .ctor

  Constructor: .ctor

  Constructor: .ctor

  Constructor: .ctor

  Property: PermissionEntries

  Type:  ServiceControllerPermissionAccess

  Field: value__

  Type:  ServiceControllerPermissionAttribute

  Method: get_MachineName

  Method: set_MachineName

  Method: get_PermissionAccess

  Method: set_PermissionAccess

  Method: get_ServiceName

  Method: set_ServiceName

  Method: CreatePermission

  Constructor: .ctor

  Property: MachineName

  Property: PermissionAccess

  Property: ServiceName

  Type:  ServiceControllerPermissionEntry

  Method: get_MachineName

  Method: get_PermissionAccess

  Method: get_ServiceName

  Constructor: .ctor

  Constructor: .ctor

  Property: MachineName

  Property: PermissionAccess

  Property: ServiceName

  Type:  ServiceControllerPermissionEntryCollection

  Method: get_Item

  Method: set_Item

  Method: Add

  Method: AddRange

  Method: AddRange

  Method: Contains

  Method: CopyTo

  Method: IndexOf

  Method: Insert

  Method: Remove

  Property: Item

  Type:  ServiceControllerStatus

  Field: value__

  Type:  ServiceInstaller

  Method: get_DisplayName

  Method: set_DisplayName

  Method: get_Description

  Method: set_Description

  Method: get_ServicesDependedOn

  Method: set_ServicesDependedOn

  Method: get_ServiceName

  Method: set_ServiceName

  Method: get_StartType

  Method: set_StartType

  Method: get_DelayedAutoStart

  Method: set_DelayedAutoStart

  Method: CopyFromComponent

  Method: Install

  Method: IsEquivalentInstaller

  Method: Rollback

  Method: Uninstall

  Constructor: .ctor

  Property: DisplayName

  Property: Description

  Property: ServicesDependedOn

  Property: ServiceName

  Property: StartType

  Property: DelayedAutoStart

  Type:  ServiceProcessDescriptionAttribute

  Method: get_Description

  Constructor: .ctor

  Property: Description

  Type:  ServiceProcessInstaller

  Method: get_HelpText

  Method: get_Password

  Method: set_Password

  Method: get_Account

  Method: set_Account

  Method: get_Username

  Method: set_Username

  Method: CopyFromComponent

  Method: Install

  Method: Rollback

  Constructor: .ctor

  Property: HelpText

  Property: Password

  Property: Account

  Property: Username

  Type:  ServiceStartMode

  Field: value__

  Type:  ServiceType

  Field: value__

  Type:  SessionChangeReason

  Field: value__

  Type:  SessionChangeDescription

  Method: get_Reason

  Method: get_SessionId

  Method: Equals

  Method: GetHashCode

  Method: Equals

  Property: Reason

  Property: SessionId

  Type:  TimeoutException

  Constructor: .ctor

  Constructor: .ctor

  Constructor: .ctor

  Type:  ServiceInstallerDialogResult

  Field: value__

  Type:  ServiceInstallerDialog

  Method: get_Password

  Method: set_Password

  Method: get_Result

  Method: get_Username

  Method: set_Username

  Constructor: .ctor

  Property: Password

  Property: Result

  Property: Username

  Type:  FXAssembly

  Type:  ThisAssembly

  Type:  AssemblyRef

  Type:  ResDescriptionAttribute

  Method: get_Description

  Constructor: .ctor

  Property: Description

  Type:  ResCategoryAttribute

  Constructor: .ctor

  Type:  Res

  Type:  ExternDll

  Type:  HResults

  Type:  StructFormat

  Field: value__

  Type:  ENUM_SERVICE_STATUS

  Constructor: .ctor

  Field: serviceName

  Field: displayName

  Field: serviceType

  Field: currentState

  Field: controlsAccepted

  Field: win32ExitCode

  Field: serviceSpecificExitCode

  Field: checkPoint

  Field: waitHint

  Type:  ENUM_SERVICE_STATUS_PROCESS

  Constructor: .ctor

  Field: serviceName

  Field: displayName

  Field: serviceType

  Field: currentState

  Field: controlsAccepted

  Field: win32ExitCode

  Field: serviceSpecificExitCode

  Field: checkPoint

  Field: waitHint

  Field: processID

  Field: serviceFlags

  Type:  QUERY_SERVICE_CONFIG

  Constructor: .ctor

  Field: dwServiceType

  Field: dwStartType

  Field: dwErrorControl

  Field: lpBinaryPathName

  Field: lpLoadOrderGroup

  Field: dwTagId

  Field: lpDependencies

  Field: lpServiceStartName

  Field: lpDisplayName

  Type:  SERVICE_TABLE_ENTRY

  Constructor: .ctor

  Field: name

  Field: callback

  Type:  LSA_UNICODE_STRING

  Constructor: .ctor

  Field: length

  Field: maximumLength

  Field: buffer

  Type:  LSA_UNICODE_STRING_withPointer

  Constructor: .ctor

  Field: length

  Field: maximumLength

  Field: pwstr

  Type:  LSA_OBJECT_ATTRIBUTES

  Constructor: .ctor

  Field: length

  Field: rootDirectory

  Field: pointerLsaString

  Field: attributes

  Field: pointerSecurityDescriptor

  Field: pointerSecurityQualityOfService

  Type:  SERVICE_DESCRIPTION

  Field: description

  Type:  SERVICE_DELAYED_AUTOSTART_INFO

  Field: fDelayedAutostart

  Type:  SERVICE_FAILURE_ACTIONS

  Field: dwResetPeriod

  Field: rebootMsg

  Field: command

  Field: numActions

  Field: actions

  Type:  SC_ACTION

  Field: type

  Field: delay

  Type:  WTSSESSION_NOTIFICATION

  Constructor: .ctor

  Field: size

  Field: sessionId

  Type:  SafeServiceHandle

  Type:  DeferredHandlerDelegate

  Method: Invoke

  Method: BeginInvoke

  Method: EndInvoke

  Constructor: .ctor

  Type:  DeferredHandlerDelegateCommand

  Method: Invoke

  Method: BeginInvoke

  Method: EndInvoke

  Constructor: .ctor

  Type:  DeferredHandlerDelegateAdvanced

  Method: Invoke

  Method: BeginInvoke

  Method: EndInvoke

  Constructor: .ctor

  Type:  UnsafeNativeMethods

  Type:  ServiceNameConverter

  Method: CanConvertFrom

  Method: ConvertFrom

  Method: GetStandardValues

  Method: GetStandardValuesExclusive

  Method: GetStandardValuesSupported

  Constructor: .ctor       

最后,记得C#编译器发出元数据和IL代码。元数据存储在一堆表。当你建立一个程序集或模块,您正在使用的编译器将创建一个类型定义表,字段定义表,方法定义表,等等。 System.Reflection命名空间中包含了几种类型,让您编写代码,以反映(或解析)这些元数据表。实际上,这个命名空间中的类型提供了程序集或模块中元数据的对象模型。使用这些类型的对象模型,您可以轻松地枚举类型定义元数据表中的所有类型。然后为每个类型,可以获取其基本类型,它实现的接口和类型相关的标志。在System.Reflection命名空间中的其他类型允许你查询的类型的字段,方法,属性,并通过分析相应的元数据表的事件。如果你要编写一个组件,你可以利用,然后转储大会和研究它的信息。用来做完全是一个宝贵的工具。NET的反射。参考文献专业。NET Framework 2.0中,乔达菲的书面历史8月27日,2010年:战后初期

回答

评论会员: 时间:2
新手没问题 - 大家都开始某处(!,大多是,我们没有任何挑战你尝试什么附近开始)

首先要注意的是,在MSDN页面的示例代码的C / C,而不是C#。这是一个很大的区别,示例代码将不会编译在C#类库。所以,你要么创建一个DLL使用C / C,或转化为等价的C#代码的C代码。

这两种方法前,你需要创建在其中粘贴示例代码从MSDN页面的非托管(三)DLL。希望样本是完整和正确的,而且会产生明显的效果,可以借鉴。要调用到这样的一个C#控制台应用程序的DLL,你需要使用P / Invoke来参考到DLL的入口点(S),你会从C#中使用。

跳深结和创建从样品。NET / C#的DLL,您也将使用P / Invoke的,但这个时候,引用调用SetWindowsHookEx和任何其他的Windows方法将被调用。您需要了解
StructLayout属性,IntPtr和无疑其他互操作所需的晦涩难懂的细节。

要明白为什么页面说,从您的控制台应用程序使用一个单独的DLL,您需要了解原生DLL的性质(这是从大异其趣。NET程序集编译成DLL),DLL和EXE如何不同。 。NET程序员,这是有点低层次的东西,但值得理解。我没有安装Windows挂钩自己,所以在这里我只是猜测,但EXE和DLL的"看"到Windows(不是猜测)不同,所以调用SetWindowsHookEx方法可能只是不工作,如果它是从一个EXE调用(
这是猜测)。
在安装一个窗钩,你告诉Windows的"这里的一些有效的代码(DLL的),这里是哪里来跳时,钩子是发射" - 并从这个角度的Windows只有了解本土的东西(和不知道的所有东西。NET)。当Windows要调用您的钩子,它需要确定DLL是否正确初始化(你可能有全局(静态)变量和其他事情之前,安全地运行在DLL的方法,需要初始化 - 初始化初始化一个EXE,DLL是非常不同。

我们希望,所有的一些有意义的。
克里斯