c# - 从两个来源创建客户对象
问题描述
从 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# 中是不可能的,但是可以使用接口模拟它,请参阅 C# 的模拟多重继承模式。
基本思想是为您希望访问的类 B 上的成员定义一个接口(称为 IB),然后让 C 从 A 继承并通过内部存储 B 的实例来实现 IB,例如:
class C : A, IB
{
private B _b = new B();
// IB members
public void SomeMethod()
{
_b.SomeMethod();
}
}
我希望我能帮上忙。
推荐阅读
- javascript - 传递参数以导入后期绑定
- node.js - 使用 kafka-node 实现 sasl SCRAM-SHA-256 机制
- php - 如何使用 boostrap 每行只显示 3 个按钮?
- mongodb - 使用 Mongo 的 geoSpatial 查询,我如何找到交叉点的确切位置?
- jquery - 应用词缀类后,主菜单在鼠标悬停时消失
- php - google bigtable 上的多行
- javascript - 如何多次使用
- awk - '~!' 是什么 awk 中的函数
- c - 我收到此错误,“错误:'{'令牌之前的预期表达式”。我不知道为什么?语法对我来说看起来不错
- html - 需要帮助将汉堡菜单向右移动