从列表中实例化的 class 获取字段列表,并比较它们
Get a list of fields from a class that is instantiated within a list, and compare them
我有一个 IReadOnlyList
实例化 类。我想获取每个 类 中存在的所有 public
static
字段,并将它们的名称(实际的 variable/field 名称作为字符串)与另一组进行比较字符串(我们的案例来自枚举值名称)。
internal static string AttachBindablesToConfig(IReadOnlyList<Drawable> children)
{
for (int i = 0; i < children.Count; i++)
{
var type = children[i].GetType(); // Get the class type
var props = type.GetFields(); // Get fields within class
return (props[0].GetValue(null)).ToString(); // Return a specific, testing purposes
}
return "Failed";
}
// in another class
Children = new Drawable[] { new Class1(), new Class2() };
..AttachBindablesToConfig(Children); // get value and display to screen
public class Class1
{
// find these fields, and return their names (x, y, z) in a string format.
public static someClass x;
public static anotherClass y;
public static int z;
}
这种方法似乎不起作用。我想要一个关于为什么它不起作用的解释,以及一个有希望解决这个问题的明确答案。
I would like to get all the public
static
fields that exists within
each of these classes
我猜你需要包含适当的绑定标志
Specifies flags that control binding and the way in which the search
for members and types is conducted by reflection.
var fieldNames = type.GetFields(BindingFlags.Public | BindingFlags.Static)
.Select(x => x.Name)
.ToList();
注意 :我很困惑你是要名字还是要值,上面得到的是名字列表
如果你也想要这个值,你可以Select像这样
.Select(x => x.Name + " = " + x.GetValue(children[i]))
我有一个 IReadOnlyList
实例化 类。我想获取每个 类 中存在的所有 public
static
字段,并将它们的名称(实际的 variable/field 名称作为字符串)与另一组进行比较字符串(我们的案例来自枚举值名称)。
internal static string AttachBindablesToConfig(IReadOnlyList<Drawable> children)
{
for (int i = 0; i < children.Count; i++)
{
var type = children[i].GetType(); // Get the class type
var props = type.GetFields(); // Get fields within class
return (props[0].GetValue(null)).ToString(); // Return a specific, testing purposes
}
return "Failed";
}
// in another class
Children = new Drawable[] { new Class1(), new Class2() };
..AttachBindablesToConfig(Children); // get value and display to screen
public class Class1
{
// find these fields, and return their names (x, y, z) in a string format.
public static someClass x;
public static anotherClass y;
public static int z;
}
这种方法似乎不起作用。我想要一个关于为什么它不起作用的解释,以及一个有希望解决这个问题的明确答案。
I would like to get all the
public
static
fields that exists within each of these classes
我猜你需要包含适当的绑定标志
Specifies flags that control binding and the way in which the search for members and types is conducted by reflection.
var fieldNames = type.GetFields(BindingFlags.Public | BindingFlags.Static)
.Select(x => x.Name)
.ToList();
注意 :我很困惑你是要名字还是要值,上面得到的是名字列表
如果你也想要这个值,你可以Select像这样
.Select(x => x.Name + " = " + x.GetValue(children[i]))