c# – 在编译时或运行时,“T:class”是否以任何方式强制执行?

前端之家收集整理的这篇文章主要介绍了c# – 在编译时或运行时,“T:class”是否以任何方式强制执行?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在下面的代码中,我将一个struct传递给一个期望一个类的构造函数.为什么编译运行没有错误(并产生所需的输出)?
  1. class Program
  2. {
  3. static void Main()
  4. {
  5. var entity = new Foo { Id = 3 };
  6. var t = new Test<IEntity>(entity); // why doesn't this fail?
  7. Console.WriteLine(t.Entity.Id.ToString());
  8. Console.ReadKey();
  9. }
  10. }
  11.  
  12. public class Test<TEntity> where TEntity : class
  13. {
  14. public TEntity Entity { get; set; }
  15.  
  16. public Test(TEntity entity)
  17. {
  18. Entity = entity;
  19. }
  20.  
  21. public void ClearEntity()
  22. {
  23. Entity = null;
  24. }
  25. }
  26.  
  27. public struct Foo : IEntity
  28. {
  29. public int Id { get; set; }
  30. }
  31.  
  32. public interface IEntity
  33. {
  34. int Id { get; set; }
  35. }

如果我更改我的Main()方法,使其包含对ClearEntity()的调用,如下所示,它仍然不会产生错误.为什么?

  1. static void Main()
  2. {
  3. var entity = new Foo { Id = 3 };
  4. var t = new Test<IEntity>(entity);
  5. Console.WriteLine(t.Entity.Id.ToString());
  6. t.ClearEntity(); // why doesn't this fail?
  7. Console.ReadKey();
  8. }

解决方法

其中TEntity:class强制TEntity为引用类型,但IEntity等接口是引用类型.

看这里:
http://msdn.microsoft.com/en-us/library/d5x73970(v=vs.80).aspx

where T : class | The type argument must be a reference type,including any class,interface,delegate,or array type

关于你的第二个问题,你可能会认为t.ClearEntity()会失败,因为它为类型为值类型的变量赋值null,但事实并非如此.编译时类型的Entity是引用类型IEntity,运行时类型(赋值后)是null类型.所以你永远不会有Foo类型的变量但值为null.

猜你在找的C#相关文章