加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 08:22:52 所属栏目:百科 来源:网络整理
导读:在下面的代码中,我将一个struct传递给一个期望一个类的构造函数.为什么编译运行没有错误(并产生所需的输出)? class Program{ static void Main() { var entity = new Foo { Id = 3 }; var t = new TestIEntity(entity); // why doesn't this fail? Console.
在下面的代码中,我将一个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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读