我尝试了谷歌搜索和计算器,但找不到我的具体问题的答案(甚至对泛型的了解有限)
所以我发帖希望得到答案。
这是我的课
public abstract class AThemeableControl<TManager, TControl>
where TManager:AManagerTheme<TManager, TControl>
where TControl:AThemeableControl<TManager, TControl>
{
public abstract void UpdateTheme(TManager managerTheme);
}
这是管理类
public abstract class AManagerTheme<TManager, TControl>
where TManager:AManagerTheme<TManager, TControl>
where TControl:AThemeableControl<TManager, TControl>
{
public TControl[] ThemableControls;
virtual public void ApplyTheme()
{
for (int i = ThemableControls.Length-1; i >= 0; i--)
{
ThemableControls[i].UpdateTheme(this); //ERROR HERE
}
}
}
所以我可以通过类型转换来解决这个错误
ThemableControls[i].UpdateTheme((TManager) this);
但我想知道无需类型转换的解决方案,我希望这是可能的。
最佳答案
您不能删除类型转换,因为这样做不安全。这是 Actor 抛出的示例:
using System;
public abstract class AManagerTheme<TManager, TControl>
where TManager : AManagerTheme<TManager, TControl>
where TControl : AThemeableControl<TManager, TControl>
{
public TControl[] ThemableControls;
public virtual void ApplyTheme()
{
for (int i = ThemableControls.Length - 1; i >= 0; i--)
{
ThemableControls[i].UpdateTheme((TManager) this);
}
}
}
public abstract class AThemeableControl<TManager, TControl>
where TManager : AManagerTheme<TManager, TControl>
where TControl : AThemeableControl<TManager, TControl>
{
// Empty implementation; irrelevant for the question.
public void UpdateTheme(TManager managerTheme) {}
}
public class NormalTheme : AManagerTheme<NormalTheme, NormalControl>
{
}
public class NormalControl : AThemeableControl<NormalTheme, NormalControl>
{
}
public class EvilTheme : AManagerTheme<NormalTheme, NormalControl>
{
}
public class Test
{
static void Main()
{
var theme = new EvilTheme
{
ThemableControls = new[] { new NormalControl() }
};
theme.ApplyTheme();
}
}
这是您希望避免的:
public class EvilTheme : AManagerTheme<NormalTheme, NormalControl>
...但是您不能用 C# 泛型来表达它。 (我在 Protocol Buffers 的早期版本中遇到过同样的事情,其中每个“消息”类型都有相应的“构建器”类型。)C# 类型系统还不够丰富,无法表达这一点。
您可能想检查抽象类构造函数中的有效性,这样至少您知道转换会在以后起作用。但是您无法避免在某处使用不同的 TManager
来强制转换 或 。
关于c# - 在 C# generic 中传递 "this"在没有转换的情况下不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54791020/