为什么一定要在新的()约束要求的公共构造? [英] Why must the new() constraint require a public constructor?

查看:119
本文介绍了为什么一定要在新的()约束要求的公共构造?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

新的约束规定,任何   在泛型类的类型参数   声明必须有一个公共的   参数的构造函数。

The new constraint specifies that any type argument in a generic class declaration must have a public parameterless constructor.

来源: http://msdn.microsoft .COM / EN-US /库/ sd2w2ew5(V = VS.80)的.aspx

如果我想我的泛型类有一个保护参数的构造函数呢?举例来说,如果我想编写一个辛格尔顿类我附加其他类,使它们辛格尔顿取值,我不希望派生类是实例化 - 一切都应该通过 .Instance 属性

What if I wanted my generic class to have a protected parameterless constructor instead? For instance, if I want to write a Singleton class which I "attach" to other classes to make them Singletons, I don't want the derived classes to be instantiable - everything should go through the .Instance property.

internal class Singleton<T> where T : new()
{
    public static T Instance { get; private set; }

    static Singleton()
    {
        Singleton<T>.Instance = new T();
    }
}

internal class OnlyOneOfMe : Singleton<OnlyOneOfMe>
{
    protected OnlyOneOfMe()
    {
    }
}

这样,辛格尔顿&LT; T&GT; 能够创建 OnlyOneOfMe 类的唯一实例,但没有别人能(除非它是一个子类)。

This way, Singleton<T> is able to create the only instance of the OnlyOneOfMe class, but nothing else can (unless it is a subclass).

如果一个通用的父类可以访问泛型类型的保护成员?

"What if a generic parent class could access the generic type's protected members?"

推荐答案

由于是约束的定义。这有点像问为什么 T:类要求 T 是引用类型。这是真正的定义。

Because that is the definition of the constraint. It's a bit like asking why does T : class require that T be a reference type. It's true by definition.

此外,如果它不是一个公共构造函数,这将是约束的地步?该类接收类型参数 T 将无法调用构造函数,如果不是公开的。

Additionally, if it weren't a public constructor, what would be the point of the constraint? The class receiving the type parameter T wouldn't be able to call the constructor if it weren't public.

这篇关于为什么一定要在新的()约束要求的公共构造?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆