首页 > 解决方案 > 从两个来源创建客户对象

问题描述

从 2 个来源创建客户对象的最佳方法是什么。我有源 A 和源 b,我想从这两个源中创建一个新对象。

来源 A:

public class A
{
    public A(string lastName, string firstName, string street, string city)
    {
        LasetName = lastName;
        FirstName = firstName;
        Street = street;
        City = city;
    }

    public string LastName { get; set; }
    public string FirstName { get; set; }
    public string Street { get; set; }
    public string City { get; set; }
}

来源 B:

public class B
{
    public B(string lastName, string firstName, string street, string city, int shoeSize)
    {
        LastName = lastName;
        FirstName = firstName;
        Street = street;
        City = city;
        ShoeSize = shoeSize;
    }

    public string LastName { get; set; }
    public string FirstName { get; set; }
    public string Street { get; set; }
    public string City { get; set; }
    
    public int ShoeSize { get; set; }
}

因此,新对象应该从源 A 获取 LastName、FirstName、Street 以及从源 B 获取 Street、City 和 ShoeSize。

实际上,来源要大得多,我知道我可以这样做:

var a = new A("dd", "afafd", "asdf","adf");
var b = new B("dd", "afafd", "asdf","adf",22);

var custome = new Custome(a.LastName, a.FirstName, a.Street, b.City, b.ShoeSize);

但是有更好的方法吗?

标签: c#merge

解决方案


多重继承在 C# 中是不可能的,但是可以使用接口模拟它,请参阅 C# 的模拟多重继承模式。

基本思想是为您希望访问的类 B 上的成员定义一个接口(称为 IB),然后让 C 从 A 继承并通过内部存储 B 的实例来实现 IB,例如:

class C : A, IB
{
    private B _b = new B();

    // IB members
    public void SomeMethod()
    {
        _b.SomeMethod();
    }
}

我希望我能帮上忙。


推荐阅读