我有A,B,C类:
public class A
{
public int Prop1;
public int Prop2;
public int Prop3;
public int Prop4;
public int Prop5;
}
public class B:A
{
public int PropB1;
public int PropB2;
}
public class C:A
{
public int PropC1;
}
我从可用变量创建对象B,C:
var b = new B
{
Prop1 = param1,
Prop2 = param2,
Prop3 = param3,
Prop4 = param4,
Prop5 = param5,
PropB1 = param6,
PropB2 = param7,
}
var c = new C
{
Prop1 = param1,
Prop2 = param2,
Prop3 = param3,
Prop4 = param4,
Prop5 = param5,
PropC1 = param8
}
使用这种编码风格,它有重复的代码。如何避免这种情况。请帮我。感谢。
Prop1 = param1, Prop2 = param2, Prop3 = param3, Prop4 = param4, Prop5 = param5,
感谢。
答案 0 :(得分:2)
在您的类中添加构造函数。这可以在您创建实例时为您节省输入属性名称。
像这样:
public class A {
public A(int prop1, int prop2, int prop3, int prop4, int prop5) {
Prop1 = prop1;
Prop2 = prop2;
Prop3 = prop3;
Prop4 = prop4;
Prop5 = prop5
}
public int Prop1;
public int Prop2;
public int Prop3;
public int Prop4;
public int Prop5;
}
public class B : A {
public B(int prop1, int prop2, int prop3, int prop4, int prop5, int propB1, int propB2) :
base(prop1, prop2, prop3, prop4, prop5) {
PropB1 = propB1;
PropB2 = propB2
}
public int PropB1;
public int PropB2;
}
public class C : A {
public C(int prop1, int prop2, int prop3, int prop4, int prop5, int propC1) :
base(prop1, prop2, prop3, prop4, prop5) {
PropC1 = propC1;
}
public int PropC1;
}
var b = new B(param1, param2, param3, param4, param5, param6, param7);
var c = new C(param1, param2, param3, param4, param5, param8);
答案 1 :(得分:1)
这个怎么样:
public class A
{
public int Prop1;
public int Prop2;
public int Prop3;
public int Prop4;
public int Prop5;
public A()
{
}
public A(A a)
{
this.Prop1 = a.Prop1;
this.Prop2 = a.Prop2;
this.Prop3 = a.Prop3;
this.Prop4 = a.Prop4;
this.Prop5 = a.Prop5;
}
}
public class B:A
{
public int PropB1;
public int PropB2;
public B(A a) : base(a)
{
}
}
public class C:A
{
public int PropC1;
public C(A a) : base(a)
{
}
}
然后您可以像这样创建对象:
var a = new A
{
Prop1 = param1,
Prop2 = param2,
Prop3 = param3,
Prop4 = param4,
Prop5 = param5
};
var b = new B(a)
{
PropB1 = param6,
PropB2 = param7
}
var c = new C(a)
{
PropC1 = param8
}
答案 2 :(得分:0)
您可以将参数包装到另一个对象中。
class AArg {
public int prop1;
public int prop2;
public int prop3;
public int prop4;
public int prop5;
}
class A {
public A(AArg args) {
// COPY(!) the values.
prop1 = args.prop1;
prop2 = args.prop2;
prop3 = args.prop3;
prop4 = args.prop4;
prop5 = args.prop5;
prop6 = args.prop6;
}
}
class B extends A {
public int probB1;
public B(Aargs aArgs, int probB1) {
super(aArgs);
this.probB1 = probB1;
}
}
使用此模式时,重要的是复制参数包装器的内容,而不是仅将其保存为字段。如果不复制它,如果对象的创建者重用参数,则对一个对象的更改可能会影响另一个对象:
AArg arg = new AArg(1,2,3,4,5);
A a1 = new A(arg);
arg.prob1 = 10;
A a2 = new A(arg);
a2.prob2 = 20
// Now a1.prob1 == 10 and a1.prob2 == 20
您还可以使参数对象不可变,这样可以安全地存储它,但这也会使A / B / C对象(部分)不可变。