【问题标题】:Operator '==' cannot be applied to same generic type运算符“==”不能应用于相同的泛型类型
【发布时间】:2020-04-27 16:50:06
【问题描述】:

我不确定我是否了解此错误的原因或如何处理它。

我有一个通用类。

public class RadioCommandCollection<T> : List<RadioCommand<T>> where T : struct, IComparable<T>
{
    /// <summary>
    /// Sets the value associated with the selected menu item to button.
    /// </summary>
    public void SetValue(T value)
    {
        foreach (RadioCommand<T> command in this)
        {
            command.SetIsSelected(command.Value == value);
        }
    }
}

foreach 块中的行给了我一个错误:

CS0019 运算符“==”不能应用于“T”和“T”类型的操作数

请注意,RadioCommand&lt;T&gt;.Value 的类型为 T。好像我在这里只定义一次T。我不明白冲突。

我添加了IComparable&lt;T&gt; 约束,但这并没有帮助。请注意,我想将 T 限制为 enum,但这不是有效的约束。

【问题讨论】:

  • 您应该使用Comparer&lt;T&gt;.Default 来比较这些值。 Enum 是从 C# 7.3 开始的有效通用约束
  • 这能回答你的问题吗? Can't operator == be applied to generic types in C#?这个问题在这个网站上有很多重复
  • T 仅表示RadioCommandCollection&lt;T&gt;,而不是RadioCommand&lt;T&gt;,这意味着在RadioCommand&lt;T&gt; 的上下文中(例如,对于它的Value 属性),T 可以是任何遵守T for RadioCommand&lt;T&gt; 的任何约束条件,将command.Value 转换为T... 我认为。
  • @HereticMonkey:是同一类型。这些类型对我来说似乎都是明确的,并且所有 T 的定义都相同。
  • @PavelAnikhouski:没必要侮辱我。在发帖之前我花了一些时间看。我发现的没有一个与我的特殊情况兼容。

标签: c# .net generics


【解决方案1】:

最简单的方法

public class RadioCommandCollection<T> : List<RadioCommand<T>> where T : struct
{
    /// <summary>
    /// Sets the value associated with the selected menu item to button.
    /// </summary>
    public void SetValue(T value)
    {
        foreach (RadioCommand<T> command in this)
        {
            command.SetIsSelected(command.Value.Equal(value));
        }
    }
}

其他方式

public class RadioCommandCollection<T> : List<RadioCommand<T>> where T : class
{
    /// <summary>
    /// Sets the value associated with the selected menu item to button.
    /// </summary>
    public void SetValue(T value)
    {
        foreach (RadioCommand<T> command in this)
        {
            command.SetIsSelected(command.Value == value);
        }
    }
}

【讨论】:

  • @JonathanWood 编辑:结构不能被合并,只有类可以。
猜你喜欢
  • 2018-09-24
  • 1970-01-01
  • 1970-01-01
  • 2011-08-14
  • 1970-01-01
  • 1970-01-01
  • 2016-06-10
相关资源
最近更新 更多