【发布时间】:2023-01-12 23:23:38
【问题描述】:
我正在尝试在 C# 中实现 Curiously recurring template pattern(CRTP)。
这是我写的一些代码。
using System;
using System.Collections;
using System.Collections.Generic;
// Curiously recurring template pattern in c#
namespace MyApp
{
public class Program
{
public static void Main (string[] arg)
{
new Child().CallChildMethod();
}
}
public abstract class Base <T> where T: Base<T>, new ()
{
public void CallChildMethod ()
{
T t = (T)this;
t?.Method ();
}
public void Method ()
{
Console.WriteLine ("Base Method!");
}
}
public class Child: Base <Child>
{
public new void Method ()
{
Console.WriteLine ("Child Method!");
}
}
}
在输出中我得到
Base Method!
但我的代码应该打印
Child Method!
任何的想法?
预期的
我想访问 base 类中的 child 类对象而不是 overriding 基方法。
【问题讨论】:
-
请参阅上面的 2 个组合答案,它们应该可以回答您关于为什么会发生这种情况的问题。
-
另外,为什么不直接使用
virtual/override的多态性呢?new是我会说的一种代码味道。 -
@GuruStron 我在更新中覆盖了一个功能,它需要成本!
标签: c# performance class inheritance crtp