Errore del compilatore CS0313

Aggiornamento: novembre 2007

Messaggio di errore

Impossibile utilizzare il tipo 'tipo1' come parametro di tipo 'nome parametro' nel tipo o metodo generico 'tipo2'. Il tipo nullable 'tipo1' non soddisfa il vincolo di 'tipo2'. I tipi nullable non soddisfano i vincoli di interfaccia.
The type 'type1' cannot be used as type parameter 'parameter name' in the generic type or method 'type2'. The nullable type 'type1' does not satisfy the constraint of 'type2'. Nullable types cannot satisfy any interface constraints.

Un tipo nullable non è equivalente al corrispondente non nullable. Nell'esempio seguente ImplStruct soddisfa il vincolo BaseInterface ma ImplStruct? non non lo soddisfa perché Nullable<ImplStruct> non implementa BaseInterface.

Per correggere l'errore

  • Se si utilizza il codice di esempio seguente, una soluzione è specificare un oggetto ImplStruct comune come primo argomento di tipo nella chiamata a TestMethod. Quindi modificare TestMethod per creare una versione nullable di Implstruct nell'istruzione return:

    return new Nullable<T>(t);
    

Esempio

Nel codice seguente viene generato l'errore CS0313:

// cs0313.cs
public interface BaseInterface { }
public struct ImplStruct : BaseInterface { }

public class TestClass
{
    public T? TestMethod<T, U>(T t) where T : struct, U
    {
        return t;
    }
}

public class NullableTest
{
    public static void Run()
    {

        TestClass tc = new TestClass();
        tc.TestMethod<ImplStruct?, BaseInterface>(new ImplStruct?()); // CS0313
    }
    public static void Main()
    { }
}

Vedere anche

Riferimenti

Tipi nullable (Guida per programmatori C#)