Perché l'interfaccia generica non può implementare il tipo dinamico?

7

Se possibile:

IList <dynamic> = new List <dynamic>;

o

class A <T>
{
 A(T){}
}

class B: A <dynamic> {}

. Perché non è possibile farlo:

class U: IEnumerable <dynamic> {}

    
posta Ucho 12.06.2016 - 17:59
fonte

2 risposte

10

Questo non è permesso, come Chris Burrows (che ha aiutato a creare e implementare dynamic ) , spiega:

Well, for one thing, it doesn’t actually give you anything that you didn’t already have. The first thing and the second thing are already there if you implemented IEnumerable<object>. In that case, you still would have been able to define GetEnumerator the way we did, and you still can convert C to IEnumerable<dynamic> (again, because of the structural conversions). Think of it this way: if anyone ever looks directly at your type C, they are never going to “see” what interfaces you implement. They only “see” them when they cast, and at that point, your IEnumerable<dynamic> didn’t do them any good.

That’s a fine reason, but you might respond, why not let me do this anyway? Why impose this limitation that seems artificial? Good question. I encountered this for the first time when I was trying to get the compiler to emit these things, and I realized very quickly that there was no where for me to emit the [Dynamic] attribute that we use to mark dynamic types. The metadata team reported that a reading of the CLI spec seemed to indicate that the tables for interface implementations and custom attributes might have permitted it, but anyway no one we know of has ever done this, and it would have been effort expended. We have priorities and a limited budget of time, and this didn’t make the cut.

    
risposta data 12.06.2016 - 18:03
fonte
4

Il modo più semplice per pensarci: dynamic non è un tipo .

dynamic è una direttiva del compilatore che disattiva tutti i controlli in fase di compilazione e li implementa in fase di esecuzione invece.

Quando dichiari una variabile dinamica:

dynamic t = 123;

t = t.Length;    // crashes at runtime

in realtà dichiari la variabile come System.Object , quindi disattiva tutti i controlli in fase di compilazione per le espressioni che coinvolgono tale variabile:

object t = 123;

unchecked_for_errors
{
    t = t.Length;    
}

Non puoi usare <dynamic> come se fosse un tipo, perché in realtà non lo è.
Utilizza <object> invece.

    
risposta data 22.09.2016 - 11:38
fonte

Leggi altre domande sui tag