我有这个继承模型:
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
});
}
增强器在每个 Dog
/Cat
/etc 中都有很多静态代码。包括 null 检查、实例化、并发控制、性能调优等的类在所有派生类中完全相同。
狗增强器应该是静态的,因为它们适用于所有狗,而不仅仅是一只狗。猫增强器等也是如此。
但它们不能迁移到 Animal
类,因为每个派生类的扩充器都不同于其他类。如果我将 Augmenters
移动到 Animal
类,那么每个应该只属于猫的增强器也将应用于狗。
如何 DRY 这种样板代码?
我看到了something similar for C++在这里,它被称为CRTP .
最佳答案
让我试试擦干
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。
关于c# - 如何在派生类中 DRY 静态重复样板代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55085365/