考虑 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
及其子类可以正常访问方法。
1 lxilu 2020-10-03 22:55:42 +08:00 via iPhone 成语? |
3 lxilu 2020-10-04 13:40:38 +08:00 一般不会认为这是语吧,感觉成文 /成法 /惯用法更好,你这样好似句柄 |
4 nullcoder 2021-06-25 16:12:48 +08:00 666 |