c# - 为什么new()约束必须要求使用公共构造函数?

原文 标签 c# generics .net-4.0 singleton

Why must the new() constraint require a public constructor?

Disclaimer: Theoretical Question

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

Source: http://msdn.microsoft.com/en-us/library/sd2w2ew5(v=vs.80).aspx

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()
    {
    }
}

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?"

Answer

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.

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.

翻译

免责声明:理论问题


  新约束指定
  泛型类中的类型实参
  声明必须公开
  无参数构造函数。
  
  资料来源:http://msdn.microsoft.com/en-us/library/sd2w2ew5(v=vs.80).aspx


如果我想让我的通用类拥有一个受保护的无参数构造函数,该怎么办?例如,如果我想编写一个“ cc”类,然后将其“附加”到其他类以使其成为Singleton,则我不希望派生类可实例化-所有内容都应通过Singleton属性。

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()
    {
    }
}


这样,.Instance能够创建Singleton<T>类的唯一实例,但是其他无能为力(除非它是子类)。

“如果泛型父类可以访问泛型类型的受保护成员怎么办?”
最佳答案
因为那是约束的定义。这有点像问为什么T : class为什么要求T是引用类型。顾名思义,这是真的。

此外,如果它不是公共构造函数,约束的意义何在?如果类型不是公共的,则接收类型参数T的类将无法调用构造函数。
相关推荐

c# - 获取与枚举关联的字符串值?

c# - 将匿名类型附加到对象;如何找回呢?

c# - 获取今天之后第n个星期日的DateTime

c# - 在发布模式下无法获取当前的工作目录?

c# - 从周号计算月份

c# - DateTime toString()问题

c# - C#中的顺序字母

c# - 自动生成确认号

c# - 如何确保静态方法中的线程安全

c# - C#:在漫长的过程中修复白屏