c# - 将字典属性作为对象访问

标签 c# .net visual-studio intellisense

我有这个类(class):

public class Class1
{
    public Dictionary<string, Class2>  Items { get; set; }
}


public class Class2
{
    public string Code { get; set;}
    public string Name { get; set; }
}

还有这个

class Program
{
    static void Main(string[] args)
    {
        Class1 c = new Class1();
        c.Items = new Dictionary<string, Class2>();

        c.Items.Add("Item0001", new Class2() { Code = "0001", Name = "Item ABC" });
        c.Items.Add("Item0002", new Class2() { Code = "0002", Name = "Item XYZ" });
    }
}

我想知道的(我已经用谷歌搜索过了,但我找不到相关信息)是是否有办法使用 Intellisense 或类似的东西访问像这样的对象。

c.Items.Item0001.Code

最佳答案

Intellisense 不会在这件事上帮助您,因为您的字典项是在运行时定义的,因此有关此信息的信息在编译时不可用。

不过,您可以使用 ExpandoObjectdynamic

dynamic foo = new ExpandoObject();
foo.Item0001 = new Class1();
foo.Item0002 = new Class1();

var asDict = (IDictionary<string, object>)foo;
var item1 = asDict["Item0001"];

关于c# - 将字典属性作为对象访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33123385/

相关文章:

c# - 遍历列表并删除项目的正确方法

c# - 在 WPF 中,如何滚动到 FlowDocumentScrollViewer 的底部?

c# - Tao框架死了吗?

c# - 如果有 'n' 个按钮,如何在不从属性手动创建的情况下自动为按钮生成事件?

visual-studio - 为什么条件断点会在调试时降低应用程序执行速度?

mysql - 使用 Visual Basic 在 mysql 中保存 blob

c# - 任意长度字符串的基数排序

c# - 将 IEnumerable<XElement> 转换为 List<嵌套对象>

ios - Visual Studio 中没有 iphone 设备

c# - 反序列化具有混合类型的 xml 文件