反射是在程式碼中描述類型、方法和欄位的元資料的過程。命名空間 System.Reflection 可讓您取得已載入組件、其中的元素(例如類別、方法和值類型)的資料。 System.Reflection 的類別有很多,但最常用的是 Assembly、AssemblyName、ConstructorInfo、MethodInfo、ParameterInfo、EventInfo、PropertyInfo 和 MemberInfo。
static void Main(string[] args){ TypeInfo myType = typeof(TextInfo).GetTypeInfo(); IEnumerable<PropertyInfo> properties = myType.DeclaredProperties; IEnumerable<MethodInfo> methods = myType.DeclaredMethods; Console.WriteLine(myType); Console.WriteLine(properties); Console.WriteLine(methods); StringBuilder strBuilder = new StringBuilder(); Console.WriteLine(); strBuilder.Append("The properties are:"); foreach (PropertyInfo p in properties){ strBuilder.Append("" + p.Name); } strBuilder.Append(""); strBuilder.Append("The methods are:"); foreach (MethodInfo m in methods){ strBuilder.Append("" + m.Name); } Console.WriteLine(strBuilder); }
System.Globalization.TextInfo System.Reflection.PropertyInfo[] System.Reflection.MethodInfo[] The properties are: Invariant ANSICodePage OEMCodePage MacCodePage EBCDICCodePage LCID CultureName IsReadOnly ListSeparator IsAsciiCasingSameAsInvariant IsRightToLeft The methods are: get_Invariant get_ANSICodePage get_OEMCodePage get_MacCodePage get_EBCDICCodePage get_LCID get_CultureName get_IsReadOnly get_ListSeparator set_ListSeparator get_IsAsciiCasingSameAsInvariant get_IsRightToLeft System.Runtime.Serialization.IDeserializationCallback.OnDeserialization Clone ReadOnly VerifyWritable SetReadOnlyState ToLower ToLower ChangeCase ChangeCaseToLower ChangeCaseToUpper ChangeCaseCommon ChangeCaseCommon ChangeCaseCommon ToLowerAsciiInvariant ToLowerAsciiInvariant ToUpperAsciiInvariant ToUpperAsciiInvariant ToLowerAsciiInvariant ToUpper ToUpper ToUpperAsciiInvariant IsAscii PopulateIsAsciiCasingSameAsInvariant Equals GetHashCode ToString ToTitleCase AddNonLetter AddTitlecaseLetter IsWordSeparator IsLetterCategory FinishInitialization ChangeCase IsInvariantLocale
以上是如何在 C# 中使用反射來顯示方法和屬性?的詳細內容。更多資訊請關注PHP中文網其他相關文章!