无法比较通用值
如果我运行此代码,为什么会出现以下
namespace TestCode
{
public class EnumList<TEnum>
{
private IList<TEnum> _list;
public EnumList()
{
_list = new List<TEnum>();
}
public void Add(TEnum val)
{
_list.Add(val);
}
public int Get(TEnum val)
{
return (int)(from one in _list
where one == val
select one).First();
}
}
}
错误:无法将 TEnum 类型转换为 TestCode.TEnum 类型?
(顺便说一句,这是“释义”,因为我的实际代码在家里,而我在工作)
编辑:从构造函数中删除了
,因为这不是主要问题
How come if I run this code:
namespace TestCode
{
public class EnumList<TEnum>
{
private IList<TEnum> _list;
public EnumList()
{
_list = new List<TEnum>();
}
public void Add(TEnum val)
{
_list.Add(val);
}
public int Get(TEnum val)
{
return (int)(from one in _list
where one == val
select one).First();
}
}
}
Gives me an error to do with not being able to convert type TEnum to type TestCode.TEnum?
(This is 'paraphrased' by the way as my actual code is at home and I'm at work)
Edit: Removed the <TEnum>
from the constructor as that's not the main problem
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您应该在TEnum 类型。写“==”是什么意思?参考值等于吗? IComparable.Equals?成员之间相等吗?
You should put a constraint on the TEnum type. What do you mean when writing "=="? ReferenceEquals? IComparable.Equals? Memberwise equals?
省略构造函数中的
部分,因为在这种情况下,它认为您可以在构造函数和类本身上分配不同的 TEnum。有趣的是,它并没有抱怨两者同名。Ommit the
<TEnum>
part in your constructor because in this case it thinks you might be able to assign a different TEnum on the constructor and on the class itself. Funny that it does not complain about both having the same name.Get() 函数有两个问题:
你可以尝试
但是,这是危险的领域,并且不可能是类型安全的。
There's two problems with the Get()-function:
You could try
However, this is dangerous territory and will no way be typesafe.
我会更改 Get 方法的返回类型,然后您可以将结果转换为 int:
I would change the return type of the Get method, then you can just cast the result to int: