从命名空间中获取所有类并处理它们的属性

本文关键字:处理 属性 命名空间 获取 | 更新日期: 2024-09-22 14:55:59

我想从命名空间中获取所有类,所以我使用了以下代码:

var theList = Assembly.GetExecutingAssembly().GetTypes()
                  .Where(t => t.Namespace == myNameSpace)
                  .ToList();

它是有效的,但当我在这个列表中循环时,我想创建list列表中每个类的实例或调用构造函数,例如调用它们的方法或属性。

Ofc这个代码不起作用,但这是我的目的。

foreach (Type t in theList)
        {
            description += t.Description;
        }

@编辑我做到了:

        var theList = Assembly.GetExecutingAssembly().GetTypes()
              .Where(t => t.Namespace == myNameSpace)
              .ToList();
        foreach (Type t in theList)
        {
            Command instance = (Command)Activator.CreateInstance(t);
            result += Environment.NewLine + instance.Name + " - " + instance.Description;
        }

从命名空间中获取所有类并处理它们的属性

要创建类的实例,可以调用Activator.CreateInstance()

还有一个很好的扩展方法,我用它来从对象中获取属性和值:

/// <summary>
///     Gets all public properties of an object and and puts them into dictionary.
/// </summary>
public static IDictionary<string, object> ToDictionary(this object instance)
{
    if (instance == null)
        throw new NullReferenceException();
    // if an object is dynamic it will convert to IDictionary<string, object>
    var result = instance as IDictionary<string, object>;
    if (result != null)
        return result;
    return instance.GetType()
        .GetProperties()
        .ToDictionary(x => x.Name, x => x.GetValue(instance));
}