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

2020-10-03 21:23:28 +08:00
 geelaw

考虑 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# 里做出等价实现,满足:

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

详见 全文(英文)

1920 次点击
所在节点    分享发现
4 条回复
lxilu
2020-10-03 22:55:42 +08:00
成语?
geelaw
2020-10-04 00:18:01 +08:00
@lxilu #1 idiom
lxilu
2020-10-04 13:40:38 +08:00
一般不会认为这是语吧,感觉成文 /成法 /惯用法更好,你这样好似句柄
nullcoder
2021-06-25 16:12:48 +08:00
666

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/712402

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX