Why are type parameters not allowed in constructors?

There are parameter types for methods. Why are there no type parameters for constructors?

Example

I think there are several (not many) examples where it would be useful. My current problem was this:

internal class ClassA
{
   private readonly Delegate _delegate;

   public ClassA<T>(Func<T> func)
   {
     _delegate = func;
   }
}

A is Delegateenough for my class. But to pass it as a group of methods, I need to define the parameter as Func<T>.

+5
source share
5 answers

After reading the C # spec, it really makes sense, but can be confusing.

, , .

class C<T>
{ 
}

C<T> - , .

C<String> c = new C<String>();

C<T>, , C<String>. Generics - , .

.

class C
{
    public C<T>() 
    {
    }
}

, , .

C c = new C<String>();

implicit explicit C C<String>? . .

C - , . , , C<String> C?

, , .

internal class Class<T> 
{
    private readonly Delegate _delegate;

    public Class(Func<T> function) 
    {
        _delegate = function;
    }
}

, Class<T>, .

Func<String> function = new Func<String>(() => { return String.Empty; });
Class<String> c = new Class<String>(function);

, , .

Func<String> function = new Func<String>(() => { return String.Empty; });
Class c = new Class<String>(function);

Class<String>, C, implicit explicit . , C .

, .

class C<T>
{
    public C<T>() 
    {
    }
}

, , .

C<String> c = new C<String>();

.

public C<String>() 
{
}

:

C<String> c = new C<String>(); // We just used the closed type constructor

, , - .

class C<T>
{
    public C<U>() 
    {
    }
}

// ???
C<String> c = new C<Int32>();

, , . , , , , , , , , .

, , .

+2

, , , .

, , , . , , , , Object .

... , , , .:\ , , , ... , , ( 1 ).

+2

, , , .

, , . , , ++, .

, "templated" factory.

+2

Func <T> . , , Func <T> . , .

class Program {
        static void Main(string[] args) {
            Func<int> i = () => 10;
            var a1 = new ClassA(i);

            Func<string> s = () => "Hi there";
            var a2 = new ClassA(s);            
        }
    }

    internal class ClassA {
        private readonly Delegate _delegate;

        public ClassA(Delegate func) { // just pass in a delegate instead of Func<T>
            _delegate = func;
        }
    }
+1

,

internal class ClassA<T>
{
 private readonly Delegate _delegate;

  public ClassA(Func<T> func)
  {
    _delegate = func;
  }
}

0

All Articles