使用反射到字典的新实例 (c#)

New Instances using Reflexion into Dictionary (c#)

我使用反射来加载一些特定的 classes 并为每个找到的 class 创建新的实例。这里代码

class 计划 {

static void Main(string[] args)
{
 
 Container typeContainer = new Container(); // Where i want set the instances

 GetType().Assembly.GetTypes()
                 .Where(type => type.IsClass) //Filter by class
                 .Where(type => type.Name.EndsWith("Model")) // Another Filter by class name 
                 .ToList() // Set found Types in to a List
                 .ForEach(modelType => {
                     // for each Type then create a new instance using the fullname                
                     object component = viewModelType.Assembly.CreateInstance(modelType.FullName);
                     // Then add the instance into the typeContainer
                     typeContainer.AddComponent(component);
                 });  
}


public class Container {

        private Dictionary<Type, object> Component { get; } = new Dictionary<Type, object>();

        public void AddComponent<T>(T componentName)
        {
            Component[typeof(T)] = componentName;
        }

}    

}

所以 Reflexion 逻辑运行良好,class 将找到我需要的那些。

问题是我想使用“AddComponent”添加实例将只添加其中之一。

问题是:

  1. 例如,当使用反射时我发现了一些元素,为什么只将其中之一添加到 typeContainer 中?

  2. 为什么 typeContainer.AddComponent(component) 像 typeContainer.AddComponent(new AnotheClassName()) 一样工作,有什么不同?

  3. 使用反射可能会得到与 typeContainer.AddComponent(new AnotheClassName()) 相同的结果?

我放了一些调试屏幕截图来提供有关调试结果的更多信息,它与代码 postet 没有 100 相同,但它只是看到使用反射的列表具有例如 3 个元素,但元素 typeContainer 刚刚添加然后,在循环之后。

感谢提前

(项目使用.net Framework 4.5)

最好的问候 Javanto

如果您将 AddComponent 更改为:

,它将起作用
        public void AddComponent(object instance)
        {
            Component[instance.GetType()] = instance;
        }