【问题标题】:How to count Number of global variables exist in class of c#如何计算c#类中存在的全局变量的数量
【发布时间】:2020-08-15 23:06:04
【问题描述】:

我想知道如何计算我调用的类中存在的全局变量的数量。

我将参数与几种类型的继承类一起使用,它们是不同数量的变量。

如果可能的话,我想获取变量的名称..

public class MotherClass
{
    public int motherAge;
}

public class ChildClass : MotherClass {
    public int childAge;
    public string childName;
}

public void Main(MotherClass person) { 
    //count number of variable exist in "person"
    //get name of variables exist in "person"
}

【问题讨论】:

标签: c# class global-variables


【解决方案1】:

我假设“类中的全局变量”是指像 public int motherAge; 这样的公共字段

using System.Reflection;
using System.Linq;
MotherClass person = new MotherClass();
var fields = person.GetType().GetFields().Where(i => i.IsPublic);
// Do something with fields.Count

foreach (FieldInfo item in fields)
{
  // Do something with item.Name;
}


【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-24
    • 1970-01-01
    • 1970-01-01
    • 2020-05-20
    • 1970-01-01
    • 2019-03-25
    相关资源
    最近更新 更多