将类的属性转换为列表 [英] convert properties of class to list

查看:79
本文介绍了将类的属性转换为列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hello All,



i在我的项目中有这个课程



Hello All,

i have this classes in my project

public class A{
    public A(B b, C c) {
            this.b = b;
            this.c = c;
        }
    B b;
    C c;
}

public class B{
    public B(DataRow row) {
            if (row.Table.Columns.Contains("UserName"))
                this.UserName = row["UserName"].ToString();

            if (row.Table.Columns.Contains("Password"))
                this.Password = row["Password"].ToString();
        }
    public string UserName { get; set; }
    public string Password { get; set; }

    public object MyToObject(){
    }
}

public class C{
    public C(DataRow row) {
            if (row.Table.Columns.Contains("UserName"))
                this.UserName = row["UserName"].ToString();

            if (row.Table.Columns.Contains("Password"))
                this.Password = row["Password"].ToString();
        }
    public string UserName { get; set; }
    public string Password { get; set; }
}





然后,我想把一个对象作为在A类中声明的MyToObject函数的输出,

输出对象包含b和c的所有属性,如下所示:





then, i want to take an object as output from MyToObject function that is declared in Class A,
that the output object contains all of the properties of b and c, like this:

output object = {b.UserName, b.PassWord, c.UserName, c.PassWord}

推荐答案

这将为您提供一个属性列表:



This will give you a list of properties:

PropertyInfo[] propsB = typeof(b).GetProperties(BindingFlags.Public | BindingFlags.Instance);
PropertyInfo[] propsC = typeof(c).GetProperties(BindingFlags.Public | BindingFlags.Instance);





然后将它们放入列表...





Then to put them into a list...

List<string> propNames = new List<string>();

foreach (PropertyInfo p in propsB)
{
    propNames.Add("b." + p.Name);
}

foreach (PropertyInfo p in propsC)
{
    propNames.Add("c." + p.Name);
}





你有它,一个名为propNames的列表,包含b类和c类的所有公共实例属性。







如果你想从属性中创建动态对象,那就是更困难,需要使用框架发射功能和低级MSIL。



这里的最终目标是什么?您是否尝试基于静态代码创建动态对象?如果类是众所周知的,为什么还要创建一个具有其他两个类的属性的对象?



And there you have it, a list called propNames with all the public instance properties of class b and class c.



If you want to create a dynamic object from the properties, that's something much more difficult and requires using the framework Emit functions and low level MSIL.

What is the ultimate goal here? Are you trying to create a dynamic object based on static code? Why would you want to create an object with the properties of the two other classes if the classes are well known?


这篇关于将类的属性转换为列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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