gpt4 book ai didi

c# - 通过反射获取继承类的所有单例

转载 作者:太空宇宙 更新时间:2023-11-03 21:57:45 25 4
gpt4 key购买 nike

我有以下场景:

class Cow : Animal
{
public int animalID;
private static Cow instance;
public static Cow Instance
{
get
{
if (instance == null) instance = new Cow();
return instance;
}
}
private Cow() { }
}

Cow是继承自 Animal 的普通单例.我需要的是:Dictionary<int, Animal>所有继承自 Animal 类型的单例,这样,a) 列表首先填充所有现有的单例[已经被实例化],并且 b) 一个方法添加到我的字典项目还没有被实例化。

对于已实现的 Cow、Goat 和 Zebra 类,我想要这样的行为:

public class Cow : Animal { ... }
public class Goat : Animal { ... }
public class Zebra : Animal { ... }

public static class AnimalManagement
{
static Dictionary<int, Animal> zoo = new Dictionary<int, Animal>();
static void FillDictionary();
static Animal GetAnimalID(int animalID);
}

public Main()
{
var a1 = Cow.Instance;
var a2 = Goat.Instance;

AnimalManagement.FillDictionary();
// Now, zoo.Count() == 2

// Suppose I seeking for Zebra, with animalID == 5:
Animal zebra = AnimalManagement.GetAnimalID(5);
// Thus, zoo.Count() == 3 and zeebra singleton was
// instantiated and added to internal dic of AnimalManagement.
}

所以我想在运行时通过反射来填充字典。有可能吗我的 friend 们?

提前致谢!

最佳答案

本质上:

var types = myAssembly.GetTypes(t => typeof(Animal).IsAssignableFrom(t) && !t.IsAbstract);
var instances = types.Select(t => t.GetProperty("Instance", B.Static).GetValue(null, null));

关于c# - 通过反射获取继承类的所有单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11526617/

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