c# - 如何在派生类中 DRY 静态重复样板代码?

标签 c# oop dry object-oriented-analysis

我有这个继承模型:

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/

相关文章:

c# - Unity3d超时处理WWW

c# - 实现规范设计模式以检查一系列字符串属性

参数中的 Java "new"关键字

go - 如何组合两个仅参数类型不同的函数

objective-c - 使用 CFBundleDocumentTypes 过滤拖放 NSView

python - 用 Python 编写 DRY 代码

c# - 在多个线程上运行 COM 组件控件

c# - 如何使用 join 加速 LINQ 查询?

c# - 统一的 Firebase 身份验证登录总是返回一个新用户

c# - 为什么 Nullable 类型必须有结构约束