将类的属性转换为单个对象

时间:2013-06-19 19:34:25

标签: c# asp.net

我的项目中有这些课程:

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("Property3 "))
            this.Property3 = row["Property3 "].ToString();

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

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

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

我想将一个对象作为MyToObject函数的输出,该函数在类A中声明;该输出对象包含bc的所有属性,如下所示:

output object = {b.Property3 , b.Property4 , c.Property1 , c.Property2 }

2 个答案:

答案 0 :(得分:0)

除非我遗漏了什么,否则你就得到了它:

public dynamic MyToObject(B b, C c)
{
    return new
    {
        BUserName = b.UserName,
        BPassword = b.PassWord,
        CUserName = c.UserName,
        CPassword = c.PassWord
    }
}

现在您已经创建了一个dynamic对象,您可以像这样使用它:

var o = a.MyToObject(b, c);
Console.WriteLine(o.BUserName);

答案 1 :(得分:0)

试试这个:

public class D
{
    public string UserNameB { get; set; }
    public string PasswordB { get; set; }
    public string UserNameC { get; set; }
    public string PassWordC { get; set; }
    public D(B b, C c)
    {
        UserNameB = b.UserName;
        PasswordB = b.PassWord;
        UserNameC = c.UserName;
        PassWordC = c.PassWord;
    }
}

然后你的ToMyObject方法就可以了:

public static D ToMyObject(B b, C c)
{
    return new D(b, c);
}

或者你也可以使用Tuple<B, C>

public static Tuple<B, C> ToMyObject(B b, C c)
{
    return Tuple.Create(b, c);
}

你也可能有点厚颜无耻并使用匿名对象,但这非常危险:

public dynamic MyToObject(B b, C c)
{
    return new { UserNameB = b.UserName, PassWordB = b.PassWord,
        UserNameC = c.UserName, PassWordC = c.PassWord }
}