运算符'=='不能应用于相同的通用类型

问题描述 投票:0回答:1

我不确定我是否了解此错误的原因或解决方法。

我有一个通用类。

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<T>.Value的类型为T。好像我在这里只定义了T。我没有冲突。

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

c# .net generics
1个回答
0
投票

最简单的方法

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.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);
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.