c# - 在 C# generic 中传递 "this"在没有转换的情况下不起作用

标签 c#

我尝试了谷歌搜索和计算器,但找不到我的具体问题的答案(甚至对泛型的了解有限)

所以我发帖希望得到答案。

这是我的课

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/

相关文章:

c# - 如何在 DataGridView 中格式化带有最大值和最小值的小数列?

c# - 处理器架构不匹配构建错误

c# - 在 C#6 中使用命名参数进行字符串插值

c# - ExecuteNonQuery 不起作用

c# - 访问通用对象参数

c# - 比较出错 c# Dictionary<String, string[]>

c# - 何时更改 Generate Serialization Assembly 值?

c# - C# 中 Excel 函数 ROUNDDOWN(number, num_digits) 的等价物是什么?

c# - 从文件路径中删除 'head' 目录

c# - 最小起订量和设置数据库上下文