我有一些课程做同样的工作。只有一些属性是不同的。 我应该使用接口来避免代码一次又一次地重写吗? 我是面向对象编程的新手,很抱歉,如果这个问题对于stackoverflow来说太容易了。
你能不能帮助我正确地实现这个实现,所以我不需要为所有类重写方法?
以下是我案例的示例类:
public class Class1
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
public string Prop3 { get; set; }
public Class1()
{
Prop1 = "Class 1 Property 1";
Prop2 = "Class 1 Property 2";
Prop2 = "Class 1 Property 3";
}
public void Method(string variable)
{
Console.WriteLine(this.Prop1);
Console.WriteLine(this.Prop2);
Console.WriteLine(this.Prop3);
}
}
public class Class2
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
public string Prop3 { get; set; }
public Class2()
{
Prop1 = "Class 2 Property 1";
Prop2 = "Class 2 Property 2";
Prop2 = "Class 2 Property 3";
}
public void Method(string variable)
{
Console.WriteLine(this.Prop1);
Console.WriteLine(this.Prop2);
Console.WriteLine(this.Prop3);
}
}
public class Class3
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
public string Prop3 { get; set; }
public Class3()
{
Prop1 = "Class 3 Property 1";
Prop2 = "Class 3 Property 2";
Prop2 = "Class 3 Property 3";
}
public void Method(string variable)
{
Console.WriteLine(this.Prop1);
Console.WriteLine(this.Prop2);
Console.WriteLine(this.Prop3);
}
}
答案 0 :(得分:1)
你绝对可以重复使用并避免干呕。
public abstract class Base {
public string Prop1 { get; set; }
public string Prop2 { get; set; }
public string Prop3 { get; set; }
public void Method(string variable) {
Console.WriteLine(this.Prop1);
Console.WriteLine(this.Prop2);
Console.WriteLine(this.Prop3);
}
}
public class Class1 : Base {
public Class1() {
Prop1 = "Class 1 Property 1";
Prop2 = "Class 1 Property 2";
Prop2 = "Class 1 Property 3";
}
}
public class Class2 : Base {
public Class2() {
Prop1 = "Class 2 Property 1";
Prop2 = "Class 2 Property 2";
Prop2 = "Class 2 Property 3";
}
}
public class Class3 : Base {
public Class3() {
Prop1 = "Class 3 Property 1";
Prop2 = "Class 3 Property 2";
Prop2 = "Class 3 Property 3";
}
}