c# – 在通用接口中实现Nullable类型

前端之家收集整理的这篇文章主要介绍了c# – 在通用接口中实现Nullable类型前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
所以在前面的一个问题中,我问到一个通用的接口是用一个public class和bingo来实现的.然而,我想要传递的类型之一是内置的可空类型之一,如:int,Guid,String等.

这是我的界面:

  1. public interface IoUrTemplate<T,U>
  2. where T : class
  3. where U : class
  4. {
  5. IEnumerable<T> List();
  6. T Get(U id);
  7. }

所以当我实现这样的时候:

  1. public class TestInterface : IoUrTemplate<MyCustomClass,Int32>
  2. {
  3. public IEnumerable<MyCustomClass> List()
  4. {
  5. throw new NotImplementedException();
  6. }
  7.  
  8. public MyCustomClass Get(Int32 testID)
  9. {
  10. throw new NotImplementedException();
  11. }
  12. }

我收到错误消息:类型“int”必须是引用类型,以便在通用类型或方法’TestApp.IoUrTemplate’中将其用作参数’U’

我试图推断Int32的类型,但同样的错误.有任何想法吗?

解决方法

我不会这样做,但它可能是让它上班的唯一方法.
  1. public class MyWrapperClass<T> where T : struct
  2. {
  3. public Nullable<T> Item { get; set; }
  4. }
  5.  
  6. public class MyClass<T> where T : class
  7. {
  8.  
  9. }

猜你在找的C#相关文章