【问题标题】:What does new() in method name means C# syntax [duplicate]方法名称中的 new() 是什么意思 C# 语法 [重复]
【发布时间】:2020-01-08 13:19:33
【问题描述】:

我正在阅读库代码,我看到了以下语法。我在 Google 上搜索了很多以找出语法名称,但我没有找到任何东西。任何帮助将不胜感激。

        /// <summary>
        /// Returns a singleton object that is used to manage the creation and
        /// execution of setup
        /// </summary>
        /// <typeparam name="TMvxSetupSingleton">The platform specific setup singleton type</typeparam>
        /// <returns>A platform specific setup singleton</returns>
        protected static TMvxSetupSingleton EnsureSingletonAvailable<TMvxSetupSingleton>()
           where TMvxSetupSingleton : MvxSetupSingleton, new()
        {
            // Double null - check before creating the setup singleton object
            if (Instance != null)
                return Instance as TMvxSetupSingleton;
            lock (LockObject)
            {
                if (Instance != null)
                    return Instance as TMvxSetupSingleton;

                // Go ahead and create the setup singleton, and then
                // create the setup instance. 
                // Note that the Instance property is set within the 
                // singleton constructor
                var instance = new TMvxSetupSingleton();
                instance.CreateSetup();
                return Instance as TMvxSetupSingleton;
            }
        }

请注意, new () {。这是什么意思?

【问题讨论】:

    标签: c# syntax new-operator


    【解决方案1】:

    来自 Microsoft 文档

    where 子句还可以包含构造函数约束 new()。该约束使得使用 new 运算符创建类型参数的实例成为可能。 new() 约束让编译器知道提供的任何类型参数都必须具有可访问的无参数构造函数。例如:

    public class MyGenericClass<T> where T : IComparable<T>, new()
    {
        // The following line is not possible without new() constraint:
        T item = new T();
    }
    

    new() 约束出现在 where 子句的最后。 new() 约束不能与结构或非托管约束结合使用。所有满足这些约束的类型都必须有一个可访问的无参数构造函数,这使得 new() 约束变得多余。

    https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/where-generic-type-constraint

    【讨论】:

      【解决方案2】:

      根据 MSDN:

      new 约束指定泛型类声明中的类型参数必须具有公共无参数构造函数。要使用new 约束,类型不能是抽象的。

      当泛型类时,将new 约束应用于类型参数 创建该类型的新实例,如下例所示:

      class ItemFactory<T> where T : new()
      {
          public T GetNewItem()
          {
              return new T();
          }
      }
      

      当你将new()约束与其他约束一起使用时,必须最后指定:

      public class ItemFactory2<T>
          where T : IComparable, new()
      {  }
      

      More informations here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-05-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-13
        • 2010-09-22
        • 1970-01-01
        • 2012-01-05
        相关资源
        最近更新 更多