【问题标题】:new() keyword in the base declaration statement in C# [duplicate]C#中基本声明语句中的new()关键字[重复]
【发布时间】:2017-08-18 09:21:31
【问题描述】:

我想知道下面的 new() 关键字。 new() 与 IDisposable 一起在基本声明语句中,其中 C : DbContext 和 IDisposedTracker。

但我想知道 new() 表达式。这是一个匿名基类声明吗?

但请注意我在 new() 旁边标记的几个箭头。这些花括号属于公共类 RepositoryBase,而不是 new()。

这里的 new() 是什么?

namespace PersonRepository
{
    public class RepositoryBase<C> : IDisposable where C : DbContext, IDisposedTracker, new()
    ->{
        public RepositoryBase()
        {
            DataContext.Database.CreateIfNotExists();
        }

        private C _DataContext;

        public virtual C DataContext
        {
            get
            {
                if (_DataContext == null || _DataContext.IsDisposed)
                {
                    _DataContext = new C();
                    AllowSerialization = true;
                    //Disable ProxyCreationDisabled to prevent the "In order to serialize the parameter, add the type to the known types collection for the operation using ServiceKnownTypeAttribute" error
                }

                return _DataContext;
            }
        }

        //partly omitted

        public void Save()
        {
            DataContext.SaveChanges();
        }

        public void Dispose()
        {
            if (DataContext != null) DataContext.Dispose();
        }
    }<-      
}

【问题讨论】:

  • _DataContext = new C(); 正在创建 C 类的 new 实例并将其分配给变量 _DataContext....

标签: c#


【解决方案1】:

new() 是一个约束 ...这意味着 C 必须是一个类并且有一个 EMPTY CONSTRUCTOR ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多