方法名称中的new()意味着C#语法[重复]

问题描述 投票:-1回答:1

我正在阅读库代码,并且看到了以下语法。我在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个回答
0
投票

从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()约束不能与struct约束或非托管约束结合使用。满足这些约束的所有类型都必须具有可访问的无参数构造函数,从而使new()约束变得多余。

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


0
投票

根据MSDN:

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

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

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

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

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

More informations here

© www.soinside.com 2019 - 2024. All rights reserved.