温馨提示:本文翻译自stackoverflow.com,查看原文请点击:c# - Printing field names of any wished class
c#

c# - 打印任何希望的类的字段名称

发布于 2020-03-27 11:11:28

假设我们有些类没有公共接口或基类。我们如何获得想要的班级名称?可能吗?我发现以下代码按预期工作但是,我想通过传递类名在函数中使用它。还有其他方法可以实现吗?

 MemberInfo[] members = typeof(objectWhatever).GetMembers();
 foreach (MemberInfo memberInfo in members.Where(p => p.MemberType == MemberTypes.Property))
 {
      Console.WriteLine("Name: {0}", memberInfo.Name); // Name: MyField
 }

我尝试编写以下内容,但在语法上不起作用

 public static List<string> FieldNames(object obj ,string className)
 {
     dynamic changedObj = Convert.ChangeType(obj, Type.GetType(className));

     MemberInfo[] members = typeof(changedObj).GetMembers();

     foreach (MemberInfo memberInfo in members.Where(p => p.MemberType == MemberTypes.Property))
     {
         Console.WriteLine("Name: {0}", memberInfo.Name); // Name: MyField
     }
}

查看更多

查看更多

提问者
snr
被浏览
19
Dmitry Bychenko 2019-07-03 22:59

首先,我们必须找到Type给定名称,例如

// className either in short format: "Form" or
//                  in full  format: "System.Windows.Forms.Form"
private static Type TypeFromName(string className)
{
  if (string.IsNullOrWhiteSpace(className))
    return null;

  return AppDomain
    .CurrentDomain
    .GetAssemblies()
    .SelectMany(asm => asm.GetTypes())
    .FirstOrDefault(t => t.Name == className || t.Namespace + "." + t.Name == className);
}

然后我们准备枚举属性:唯一的区别是我们使用tp- Type 找到而不是硬编码 typeof(objectWhatever)

 string className = ...

 Type tp = TypeFromName(className);

 if (tp != null)
 {
     var members = tp
       .GetMembers()
       .Where(p => p.MemberType == MemberTypes.Property);

     foreach (MemberInfo memberInfo in members)
     {
         Console.WriteLine("Name: {0}", memberInfo.Name); 
     }
 }
 else 
 {
     // className has not been found
 } 

发布
问题

分享
好友

手机
浏览

扫码手机浏览