【问题标题】:Get all classes from namespace and work on their properties [duplicate]从命名空间获取所有类并处理它们的属性[重复]
【发布时间】:2016-08-08 11:54:14
【问题描述】:

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

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

它正在工作,但是当我遍历这个列表时,我想为列表中的每个类创建实例或调用构造函数,例如调用它们的方法或属性。

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
  • 描述只是字符串属性。例如,我添加了这个。我的意思是我想使用 Llist 列表中的类属性和方法。
  • 您需要查看“反射”以及随之而来的所有内容。它允许您在运行时创建对象并调用方法/属性。
  • @Porqqq Description 是静态属性吗?如果您创建一个新实例,Description 将设置为默认值还是null?

标签: c# c#-4.0 c#-5.0


【解决方案1】:

要创建一个类的实例,您可以调用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));
}

【讨论】:

    猜你喜欢
    • 2011-03-22
    • 1970-01-01
    • 1970-01-01
    • 2019-07-18
    • 1970-01-01
    • 1970-01-01
    • 2020-10-03
    • 2023-03-09
    • 2018-10-19
    相关资源
    最近更新 更多