geelaw

如何在 C# 里写出零额外开销(避免虚拟方法调用)的 CRTP 成语

  •  
  •   geelaw · Oct 3, 2020 · 3121 views
    This topic created in 2051 days ago, the information mentioned may be changed or developed.

    考虑 C++ 代码

    #include<iostream>
    
    template <typename T>
    struct Base
    {
      T &Foo()
      {
        // MSVC 需要这个提示来优化 static_cast 的空指针检查。
        // __assume(this != nullptr);
        static_cast<T *>(this)->FooImpl();
        return *static_cast<T *>(this);
      }
    protected:
      ~Base() = default;
    };
    
    struct Derived : Base<Derived>
    {
    private:
      friend Base<Derived>;
      void FooImpl() { std::cout << "没有虚拟方法调用" << std::endl; }
    };
    

    问题是如何在 C# 里做出等价实现,满足:

    • 没有虚拟方法调用,或者子类可以决定 FooImpl 是否虚拟。
    • 至少在运行时保证 Base 的泛型参数是正确的子类。
    • 除非运行时使用反射作弊,否则不能破坏类的封装(需要实现有限程度的 friend),且编译期也不能破坏封装。

    第一个问题可以通过利用 CLR 对泛型参数实例化为 struct 时的优化实现,第二个则需要巧妙设置对应 struct 的接口和实现,使只有 Base 及其子类可以正常访问方法。

    详见 全文(英文)

    4 replies    2021-06-25 16:12:48 +08:00
    lxilu
        1
    lxilu  
       Oct 3, 2020 via iPhone
    成语?
    geelaw
        2
    geelaw  
    OP
       Oct 4, 2020
    @lxilu #1 idiom
    lxilu
        3
    lxilu  
       Oct 4, 2020
    一般不会认为这是语吧,感觉成文 /成法 /惯用法更好,你这样好似句柄
    nullcoder
        4
    nullcoder  
       Jun 25, 2021
    666
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3028 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 86ms · UTC 08:27 · PVG 16:27 · LAX 01:27 · JFK 04:27
    ♥ Do have faith in what you're doing.