我不确定我是否了解此错误的原因或解决方法。
我有一个通用类。
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
,但这不是有效的约束。
最简单的方法
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);
}
}
}