C#中ValueType的泛型类型约束
发布时间:2020-12-15 23:46:05 所属栏目:百科 来源:网络整理
导读:我有泛型类,限制参数使用int或long类型.我的问题是我需要在我的方法中比较这个参数类型的变量.但是编译器说我无法比较这些项目 – Operator ‘==’ cannot be applied to operands of type ‘K’ and ‘K’ 我的代码: public class MyClassT,K where T : En
我有泛型类,限制参数使用int或long类型.我的问题是我需要在我的方法中比较这个参数类型的变量.但是编译器说我无法比较这些项目 –
我的代码: public class MyClass<T,K> where T : Entity<K> //where K : ??? - what can I do? { public virtual bool MyMethod(T entity1,T entity2) { return entity1.EntityId == entity2.EntityId;//Operator '==' cannot be applied to operands of type 'K' and 'K' } } public abstract class Entity<T> { public T EntityId{get;set;} } 解决方法
您可以在
IEquatable<K> 上约束K并使用等于:
public class MyClass<T,K> where T : Entity<K> where K : IEquatable<K> { public virtual bool MyMethod(T entity1,T entity2) { return entity1.EntityId.Equals(entity2.EntityId); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |