从父对象创建子对象实例的最佳方法 [英] Best way to create instance of child object from parent object
问题描述
我正在从父对象创建子对象。所以场景是我有一个对象和一个子对象,它为我想要搜索的场景添加了一个距离属性。我选择使用继承,因为我的UI与搜索对象或对象列表等效地工作,而不是位置搜索的结果。所以在这种情况下,继承似乎是一个明智的选择。
I'm creating a child object from a parent object. So the scenario is that I have an object and a child object which adds a distance property for scenarios where I want to search. I've chosen to use inheritance as my UI works equivalently with either a search object or a list of objects not the result of a location search. So in this case inheritance seems a sensible choice.
现在我需要从 MyObject <的实例生成一个新对象
MyObjectSearch
/ code>。目前我通过逐个设置属性手动在构造函数中执行此操作。我可以使用反射,但这会很慢。有没有更好的方法来实现这种对象增强?
As present I need to generate a new object MyObjectSearch
from an instance of MyObject
. At present I'm doing this in the constructor manually by setting properties one by one. I could use reflection but this would be slow. Is there a better way of achieving this kind of object enhancement?
希望我的代码如下所示。
Hopefully my code below illustrates the scenario.
public class MyObject {
// Some properties and a location.
}
public class MyObjectSearch : MyObject {
public double Distance { get; set; }
public MyObjectSearch(MyObject obj) {
base.Prop1 = obj.Prop1;
base.Prop2 = obj.Prop2;
}
}
我的搜索功能:
public List<MyObjectSearch> DoSearch(Location loc) {
var myObjectSearchList = new List<MyObjectSearch>();
foreach (var object in myObjectList) {
var distance = getDistance();
var myObjectSearch = new MyObjectSearch(object);
myObjectSearch.Distance = distance;
myObjectSearchList.add(myObjectSearch);
}
return myObjectSearchList;
}
推荐答案
基类需要定义一个复制构造函数:
The base class needs to define a copy constructor:
public class MyObject
{
protected MyObject(MyObject other)
{
this.Prop1=other.Prop1;
this.Prop2=other.Prop2;
}
public object Prop1 { get; set; }
public object Prop2 { get; set; }
}
public class MyObjectSearch : MyObject
{
public double Distance { get; set; }
public MyObjectSearch(MyObject obj)
: base(obj)
{
this.Distance=0;
}
public MyObjectSearch(MyObjectSearch other)
: base(other)
{
this.Distance=other.Distance;
}
}
这样就可以处理所有派生的属性设置基类的类。
This way the setting of properties is handled for all derived classes by the base class.
这篇关于从父对象创建子对象实例的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!