我当时正在阅读一个库代码,我看到了下面的语法。我在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 () {。这意味着什么?
发布于 2020-01-08 13:22:00
来自Microsoft
where子句还可能包含一个构造函数约束,即new()。该约束使使用新运算符创建类型参数的实例成为可能。新的()约束让编译器知道,提供的任何类型参数都必须有一个可访问的无参数构造函数。例如:
public class MyGenericClass<T> where T : IComparable<T>, new()
{
// The following line is not possible without new() constraint:
T item = new T();
}新()约束在where子句中显示在最后。新()约束不能与struct或非托管约束组合。满足这些约束的所有类型都必须有一个可访问的无参数构造函数,从而使新()约束变得多余。
发布于 2020-01-08 13:24:09
根据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()
{ }https://stackoverflow.com/questions/59646770
复制相似问题