gpt4 book ai didi

c# - 在 C# 中获取对类中某个类型的所有对象的引用

转载 作者:太空宇宙 更新时间:2023-11-03 20:48:52 35 4
gpt4 key购买 nike

假设我有一个类,其中包含一些 Foo 类型对象的引用变量。假设我现在想要动态获取所有这些变量的列表,这意味着如果我添加一个新变量,该变量也会出现在列表中。

我试过使用反射,但我对它不是很有经验,所以我认为这是正确的方法,但我不完全确定。

public class Foo() {
public void Setup() {
// Runs some code
}
}

public class MyClass() {
public Foo a;
public Foo b;
public Foo c;
public Foo d;
public Foo e;

// Current constructor, does what I want but in a non-elegant way
MyClass() {

Foo[] foos= new Foo[] {
a,
b,
c,
d,
e
};
foreach(Foo foo in foos) {
foo.Setup();
}
}

// The constructor I want, with GetAllMembersOfType<T>() dynamically
// returning new objects as I add them to the class later
MyClass() {

Foo[] foos = GetAllMembersOfType<Foo>();
foreach(Foo foo in foos) {
foo.Setup();
}
}
}

我怎样才能创建类似 GetAllMembersOfType<T>() 的方法? ?或者至少是一种调用 Setup() 的方式在 Foo 类型的所有成员变量上?

最佳答案

使用反射获取一个类型的所有privatepublic字段,你的构造函数将变成这样:

public class MyClass() 
{
public Foo a;
public Foo b;
public Foo c;
public Foo d;
public Foo e;

MyClass()
{
Foo[] foos = GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)
.Where(fieldInfo => fieldInfo.FieldType.Equals(typeof(Foo)))
.Select(fieldInfo => fieldInfo.GetValue(this))
.Cast<Foo>()
.ToArray();

foreach(Foo foo in foos)
{
foo.Setup();
}
}
}

但是这个字段可能没有被初始化。也许在实例化时调用 Setup() 作为外部调用或构造函数调用更方便。

关于c# - 在 C# 中获取对类中某个类型的所有对象的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57637680/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com