【问题标题】:How to Display List of Classes and it properties in a propertygrid that implement an interface C#如何在实现接口 C# 的 propertygrid 中显示类列表及其属性
【发布时间】:2016-04-28 15:12:39
【问题描述】:

我有一个显示类属性的属性网格(我们称之为 MyClass)

我想在 MyClass 中有一个属性,它将包含所有实现接口的类(我们称之为 ISomething),并将在 PropertyGrid 中表示为下拉列表(当你有一个枚举时,行为相同)

接下来在列表中选择其中一个类时,将获取所选类的所有属性,并显示在propertygrid

我做了一些阅读并找到了一些关于如何获取所有类列表并创建它的实例的部分解决方案,但不确定如何使用这些实例在属性网格中创建类列表。

var instances = from t in Assembly.GetExecutingAssembly().GetTypes()
            where t.GetInterfaces().Contains(typeof(ISomething))
                     && t.GetConstructor(Type.EmptyTypes) != null
            select Activator.CreateInstance(t) as ISomething;

foreach (var instance in instances)
{
instance.Foo(); // where Foo is a method of ISomething
}

有什么建议吗?

【问题讨论】:

  • 此代码与属性网格无关。属性网格区你尝试过什么?
  • 我还没有在网格上实现,你说得对,这行不通

标签: c# class interface propertygrid


【解决方案1】:

使用Ninject:

var kernel = new StandardKernel();
kernel.Bind<ISomething>().To<Something>();
kernel.Bind<ISomething>().To<Something2>();

var instances = kernal.GetAll<ISomething>();
foreach (var instance in instances)
{
    instance.Foo();
}

【讨论】:

    【解决方案2】:

    以下代码将返回对象的List,每个对象都有类名和属性名的List

    var classesWithProperties = 
        Assembly.GetExecutingAssembly()
                .GetTypes()
                .Where(t => t.GetInterfaces().Contains(typeof(ISomething)) && t.IsClass)
                .Select(c => new { ClassName = c.FullName, Properties = c.GetProperties().Select(p => p.Name)})
                .ToList();
    

    然后你可以遍历这个集合,并按照你的意愿显示它。

    【讨论】:

    • 所以在我浏览了 classesWithProperties 中的每个对象之后,我将如何显示类列表的集合以及每个类的属性和属性值。它没有返回属性列表。另外我假设在你的代码中 Ilist 是我的情况下的 Isomething
    • 这里我做了什么 Dictionary classObject = new Dictionary();在我调用你的代码后,我执行 foreach(classesWithProperties 中的 var 字段){ classObject.Add(field.ClassName, field.Properties as ISomething);当我调用 propertygrid 调用带有字典列表的属性时,我得到了正确的名称,另一方面,我得到了 ISomthing->Value->Key 和 Value,其中没有任何值
    • 值将为空,因为要显示值,您需要有一个对象实例。即使您将使用 Activator 创建对象 - 属性也将具有默认值(我猜这没有任何意义)。
    • 你说得对我需要创建一个对象的实例来获取默认值
    • 因此,您不需要属性列表。您只需要对象列表 - 需要您 Activator 来创建它们。但如果这些类没有默认构造函数,可能会出现问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-24
    • 2017-04-02
    • 2018-01-13
    • 2018-08-21
    • 1970-01-01
    • 2010-12-08
    • 2016-01-28
    相关资源
    最近更新 更多