如何在派生类中干燥静态重复样板代码?

问题描述 投票:1回答:1

我有这个继承模型:

public class Animal
{
}

public class Dog : Animal
{
    public static List<Action<Dog>> Augmenters = new List<Action<Dog>>();
}

public class Cat : Animal
{
    public static List<Action<Cat>> Augmenters = new List<Action<Cat>>();
}

// in another place of the code, augmenters are added and configured
public static void Main (string[] args) 
{
    Dog.Augmenters.Add(dog => 
    {
         // doing something with dog
    });        
    Cat.Augmenters.Add(cat => 
    {
         // doing something with cat
    });
}

Augmenters在每个Dog / Cat / etc中都有很多静态代码。类包括空检查,实例化,并发控制,性能调优等,这些类在所有派生类中完全相同。

狗增强器应该是静止的,因为它们适用于所有狗,而不仅仅是一只狗。猫增强器等等也是如此

然而,它们不能迁移到Animal类,因为每个派生类的增强器与其他类不同。如果我将Augmenters移动到Animal类,那么每个应该只属于猫的增强器也会应用于狗。

你怎么干这种类型的样板代码?

我在这里看到something similar for C++,它被称为CRTP

c# oop dry object-oriented-analysis
1个回答
3
投票

让我试着干

class Program
{

    public abstract class Animal<T> where T : Animal<T>
    {
        public static List<Action<T>> Augmenters = new List<Action<T>>();
    }

    public class Dog : Animal<Dog>
    {

    }

    public class Cat : Animal<Cat>
    {

    }

    // in another place of the code, augmenters are added and configured
    public static void Main(string[] args)
    {
        Dog.Augmenters.Add(dog =>
        {
            Console.WriteLine("bark");
        });

        Cat.Augmenters.Add(cat =>
        {
            Console.WriteLine("meow");
        });

        Dog.Augmenters[0].Invoke(new Dog());
        Cat.Augmenters[0].Invoke(new Cat());
        Console.ReadLine();
    }
}

添加了一个抽象方法并为其类型添加了约束,至少您不必在具体类中重复Augementers的实现。

© www.soinside.com 2019 - 2024. All rights reserved.