在下面的代码中,我将一个struct传递给一个期望一个类的构造函数.为什么编译运行没有错误(并产生所需的输出)?
- class Program
- {
- static void Main()
- {
- var entity = new Foo { Id = 3 };
- var t = new Test<IEntity>(entity); // why doesn't this fail?
- Console.WriteLine(t.Entity.Id.ToString());
- Console.ReadKey();
- }
- }
- public class Test<TEntity> where TEntity : class
- {
- public TEntity Entity { get; set; }
- public Test(TEntity entity)
- {
- Entity = entity;
- }
- public void ClearEntity()
- {
- Entity = null;
- }
- }
- public struct Foo : IEntity
- {
- public int Id { get; set; }
- }
- public interface IEntity
- {
- int Id { get; set; }
- }
如果我更改我的Main()方法,使其包含对ClearEntity()的调用,如下所示,它仍然不会产生错误.为什么?
- static void Main()
- {
- var entity = new Foo { Id = 3 };
- var t = new Test<IEntity>(entity);
- Console.WriteLine(t.Entity.Id.ToString());
- t.ClearEntity(); // why doesn't this fail?
- Console.ReadKey();
- }
解决方法
其中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.