C# 填充基本属性的最佳方法是什么?
我想知道是否有人可以帮助我填充派生类的基属性的最佳方法。我想使用一种方法来填充基类的属性,无论是使用基类还是子类 下面是我要问的一个例子:C# 填充基本属性的最佳方法是什么?,c#,inheritance,C#,Inheritance,我想知道是否有人可以帮助我填充派生类的基属性的最佳方法。我想使用一种方法来填充基类的属性,无论是使用基类还是子类 下面是我要问的一个例子: public class Parent { public string Id {get; set;} } public class Child : Parent { public string Name {get; set;} } public Parent GetParent(int ID) { Parent myPare
public class Parent
{
public string Id {get; set;}
}
public class Child : Parent
{
public string Name {get; set;}
}
public Parent GetParent(int ID)
{
Parent myParent = new Parent();
//Lookup and populate
return Parent;
}
public Child GetChild(string name)
{
Child myChild = new Child();
//Use the GetParent method to populate base items
//and then
//Lookup and populate Child properties
return myChild;
}
如果您不想在
构造函数中执行此操作,请执行类似的操作
注意:构造函数
并不总是被调用,特别是当需要使用某些序列化程序对类型进行序列化时
public class Parent
{
public string Id {get; set;}
public virtual void InitPorperties() {
//init properties of base
}
}
public class Child : Base {
public override void InitProperties() {
//init Child properties
base.InitProperties();
}
}
在此之后,您可以像这样使用它:
public Parent GetParent(int ID)
{
var myParent = new Parent();
parent.InitProperties();
return myParent;
}
public Parent GetChild(int ID)
{
var child= new Child();
child.InitProperties();
return child;
}
正如它的另一面一样:调用者必须调用InitProperties
方法才能正确初始化对象
如果序列化/去序列化在您的情况下不是一个问题,请坚持使用构造函数,实际上在每种类型的构造函数中调用此方法(父类
,子类
)我想您可能有点过于复杂了。看看这段使用继承和构造函数初始化对象的代码:
public class Parent
{
public string Id {get; set;}
public Parent(string id)
{
Id = id;
}
}
public class Child : Parent
{
public string Name {get; set;}
public Child(string id, string name) : base(id) // <-- call base constructor
{
Name = name;
}
}
公共类父类
{
公共字符串Id{get;set;}
公共父项(字符串id)
{
Id=Id;
}
}
公共类子级:父级
{
公共字符串名称{get;set;}
public Child(string id,string name):base(id)//如果您不想使用标准方式
Child myChild = new Child();
myChild.Name = "name";
myChild.Id = "1";
您可以像这样通过构造函数填充它们
public class Parent
{
public Parent(string id)
{
Id = id;
}
public string Id { get; set; }
}
public class Child : Parent
{
public Child(string id, string name)
: base(id)
{
name = Name;
}
public string Name { get; set; }
}
当你说出来的时候
Child myChild = new Child("1", "name");
在我看来,这是一种非常简洁的方法。通过构造函数填充?可能的重复项可以按照sll
的建议执行,也可以采用继承路径。不要忘记构造函数链接。