0

我的项目中有这些类:

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;该输出对象包含 and 的所有属性bc如下所示:

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

2 回答 2

0

Unless I'm missing something, you've just about got it:

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

Now that you've created a dynamic object you can use it like this:

var o = a.MyToObject(b, c);
Console.WriteLine(o.BUserName);
于 2013-06-19T19:39:48.313 回答
0

Try this:

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;
    }
}

and then your ToMyObject method can just be this:

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

Or you could also use a Tuple<B, C>:

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

You could also be a bit cheeky and use anonymous objects, but that's very dangerous:

public dynamic MyToObject(B b, C c)
{
    return new { UserNameB = b.UserName, PassWordB = b.PassWord,
        UserNameC = c.UserName, PassWordC = c.PassWord }
}
于 2013-06-19T19:40:01.500 回答