如何从包含另一个结构对象的对象中查找属性并添加到C#中的字典? [英] How to find properties from object that contain another structure object and add to dictionary in C#?

查看:115
本文介绍了如何从包含另一个结构对象的对象中查找属性并添加到C#中的字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的类包含一个或多个结构的引用,并且在结构中有一些属性。

现在我想通过创建类来从嵌套对象(即结构引用)中找到属性对象并添加到词典。

有人可以帮我吗?



谢谢

tink



我的尝试:



字典

I have class that contain the reference of one or more structure and in structure have some properties.
now I want to find the properties from the nesting object(i.e structure reference) by creating the class object and add to dictionary.
can someone help me?

thanks
tink

What I have tried:

Dictionary

推荐答案

假设我们有一个如下定义的结构;



Let say we have a struct as defined below;

internal struct MyStruct
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }







课堂上使用的是什么;






Which is used in the class;

internal class MyClass
    {
        public MyStruct myStruct { get; set; }
    }





检索和更新词典可以完成;





Retrieving and updating Dictionary can be done as;

MyClass m = new MyClass();
            var required = m.myStruct.Id;

            Dictionary<int, string> dict = new Dictionary<int, string>();
            dict.Add(required, m.myStruct.Name);


private Dictionary<string, string> dict = new Dictionary<string, string>();
MyClass myClass = new MyClass();

// Get Class properties.
foreach (var prop in myClass.GetType().GetProperties())
{
	var propValue = prop.GetValue(myClass, null).ToString();
	this.dict.Add(prop.Name, propValue);
}




// Get struct properties.
var temp = myClass.myStruct;
foreach (var prop in temp.GetType().GetProperties())
{
    var propValue = prop.GetValue(temp).ToString();
    this.dict.Add(prop.Name, propValue);
}


这篇关于如何从包含另一个结构对象的对象中查找属性并添加到C#中的字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆