如何实现做相同工作的类

本文关键字:工作 何实现 实现 | 更新日期: 2023-09-27 18:09:07

我有一些类做完全相同的工作。只有一些属性不同。我应该使用接口来避免一次又一次地重写代码吗?我是一个面向对象编程的新手,所以抱歉,如果这个问题对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);
    }
} 

如何实现做相同工作的类

你绝对可以实现一些重用和避免DRY。

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";
    }
}