Is there a way to specify a T: new () constraint, but with an internal constructor?

I created a generic class that should create an instance of its implementation type, so the implementation type should have the less constructor parameter available. It looks like the new () constraint could do the job, but at the same time forcibly applying the implementation type to have an open constructor when I have an internal one (but accessible, since both of them are on the same assembly).

  • Is there a reason to make it public, rather than "accessible"?
  • Is there a way to do what I need?

Thanks in advance.

EDIT: The reason for this is because I have an X class that should be used through Singleton. The Singleton class is a generic class, and I want the X class's internal constructor to prevent external users from accessing the object in the wrong way (constructor call).

+5
source share
3 answers

This is prohibited by C #, as described in section 4.4.3 of the Bound and Unbound Types specifications.

If the constraint is a constructor constraint new(), the type Ashould not be abstractand must have an open constructor without parameters. This is true if one of the following conditions is true.

  • A - value type, since all value types have a standard default constructor
  • A is a type parameter having a cosntructor constraint
  • A - ,
  • A - , abstract public constuctor
  • A abstract .

, - . , , , , , , .

accessor internal public . public private internal, .

internal class C<T> where : T new()
{
    public C() : this(new T()) {
    }

    private C(T t) {
        // Do additional initialization
    }
}

, , private.

internal class C<T> where T : new() {
    public C() {
        T t = new T();
        InitializeClass(t);
    }

    private void InitializeClass(T t) {
        throw new NotImplementedException();
    }
}   

.

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

    internal Singleton() : this(new T()) {
    }

    private Singleton(T t) {
        Current = this;
        // Do whatever you need to with T
    }        

    public String Name {
        get;
        set;
    }
}

// Somewhere in your internal assembly
Singleton<String> singleton = new Singleton<String>();

// In an external assembly
Singleton.Current.Name = "SoMoS";

, - .

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

    internal Singleton() {
        T t = new T();
        // Do stuff with T
    }

    public String Name {
        get;
        set;
    }
}

, . . , Factory Pattern, Injection ..

+5

, ""?

, , . internal , .

, ?

, , , .

+2

, , "" , , ctor.

, , .

* T: MyBaseClassWithInternalCtor *

.

+1

All Articles