反射是在代码中描述类型、方法和字段的元数据的过程。命名空间 System.Reflection 使您能够获取有关已加载程序集、其中的元素(例如类、方法和值类型)的数据。 System.Reflection 的类有很多,但最常用的是 Assembly、AssemblyName、ConstructorInfo、MethodInfo、ParameterInfo、EventInfo、PropertyInfo 和 MemberInfo。
示例
static void Main(string[] args){
TypeInfo myType = typeof(TextInfo).GetTypeInfo();
IEnumerable properties = myType.DeclaredProperties;
IEnumerable 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# 中使用反射来显示方法和属性?的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!