【发布时间】:2019-08-01 16:41:05
【问题描述】:
我正在尝试创建一系列包装类来封装直接从数据库派生的一些类。
我想简单地将数据库对象的一个实例交给包装类的构造函数,而不必手动设置每个属性。
我无法更改数据库 B 类,它不是我的代码或部门,我必须提升 2 级管理才能与可以考虑更改它的人交谈。
我知道可以简单地暴力破解解决方案。通过在构造函数中获取基类的实例并使用该实例设置真正的基类的每个属性。像这样:
class A :B{
public A(B instance){
this.Prop1 = B.Prop1
//...
this.Prop87 = B.Prop87
}
public string doRandomWrapperFunction(){
return Prop36 + Prop49 + DateTime.Now();
}
}
但是其中一些对象有超过 100 个道具,我有大约 100 个对象我想为其创建一个包装器。所以这意味着我需要写超过 1000 行的 this.Prop59 = B.Prop59。而且它们将来可能会改变。
我想要的是这样的:
class A : B{
public A(B instance){
base = B;//This is the line that I want to compile but can't
}
public string doRandomWrapperFunction(){
return Prop36 + Prop49 + DateTime.Now();
}
}
我真的不想做类似的事情
class A{
public B BaseInstance;
public A(B instance){
this.baseInstance = B;
}
public string doRandomWrapperFunction(){
return BaseInstance.Prop36 + BaseInstance.Prop49 + DateTime.Now();
}
}
因为我到处都使用B类
string id = "1234"
B dbObject = getBFromDatabase(id); //I cant change this method.
existingCodeFunctionCall(dbObject.Prop1) //<==this times 1000
我必须将它们全部更改为:
A dbObject = new A(getBFromDatabase(id));
existingCodeFunctionCall(dbObject.BaseInstance.Prop1) //<==this times 1000
我只是想将它的声明从 B 更改为 A,如下所示:
A dbObject = new A(getBFromDatabase(id));
existingCodeFunctionCall(dbObject.Prop1)//<== this doesnt need to change
//because it automatically has all the properties of the base class.
我知道我可能会走得更远,解决方案可能与继承或基类无关,这正是我卡住的地方。
感谢您的帮助。
【问题讨论】:
-
你可以只做 new A(params),并在 A 的构造函数中调用 base(params),如 public A(int params) : base(params) {//其余的构造函数逻辑}
-
问题是我从存储库中完全形成了所有这些对象。我从不创造它们,它们已经完成了交给我。我会更改我的描述以使其更清楚。
-
您可以使用反射来做到这一点:stackoverflow.com/questions/737151/…
-
你的问题很广泛。你不能完全按照你的要求去做,而且替代方案的数量很大。有关几个建议,请参阅标记的重复项。也就是说,我看不出问题出在哪里。您仍然需要实际编写属性,这很麻烦。那么,如果您还必须为每个语句再编写一个语句来初始化它呢?但是,如果您不想这样做,最好保留对基类的引用并将所有属性委托给基类。然后你只需要处理属性实现本身,而不是初始化。
标签: c# inheritance constructor base-class