Errore del compilatore CS0119

'construct1_name' è un 'construct1', che non è valido nel contesto specificato.

Il compilatore ha rilevato un costrutto imprevisto, ad esempio il seguente:

  • Un costruttore di classe non è un'espressione di test valida in un'istruzione condizionale.

  • È stato usato un nome di classe anziché un nome di istanza per fare riferimento a un elemento di matrice.

  • Un identificatore di metodo viene usato come se fosse uno struct o una classe

Esempi

Esempio 1

L'esempio seguente genera l'errore CS0119: 'C.B()' è un metodo, che non è valido nel contesto specificato. È possibile correggere questo errore modificando il nome del metodo C.Bo usando il nome completo per la classe B , ad esempio N2.B.

namespace N2
{
    public static class B
    {
        public static void X() {}
    }
}

namespace N1
{
    public class C
    {
        void B() {}
        void M() => B.X();   // CS0119
    }
}

Esempio 2

L'esempio seguente illustra uno scenario comune in cui si verifica CS0119 quando si tenta di aggiungere nomi di classe a una raccolta di tipi. Il compilatore prevede Type istanze, non nomi di classe.

using System;
using System.Collections.Generic;

public class Page_BaseClass { }
public class Page_CRTable { }
public class Page_DBGridWithTools { }

public static class PageTypeManager
{
    public static List<Type> GetPageTypes()
    {
        List<Type> pageTypesList = new List<Type>();

        // CS0119: 'Page_BaseClass' is a type, which is not valid in the given context
        pageTypesList.Add(Page_BaseClass);
        pageTypesList.Add(Page_CRTable);
        pageTypesList.Add(Page_DBGridWithTools);

        return pageTypesList;
    }
}

Per correggere l'errore, usare il Type.GetType metodo o l'operatore typeof per ottenere Type le istanze:

using System;
using System.Collections.Generic;

public static class PageTypeManager
{
    public static List<Type> GetPageTypes()
    {
        List<Type> pageTypesList = new List<Type>();

        // Use typeof operator to get Type instances
        pageTypesList.Add(typeof(Page_BaseClass));
        pageTypesList.Add(typeof(Page_CRTable));
        pageTypesList.Add(typeof(Page_DBGridWithTools));

        return pageTypesList;
    }

    // Alternative: Load types dynamically by name
    public static List<Type> GetPageTypesByName(string[] typeNames)
    {
        List<Type> pageTypesList = new List<Type>();

        foreach (string typeName in typeNames)
        {
            Type type = Type.GetType(typeName);
            if (type != null)
            {
                pageTypesList.Add(type);
            }
        }

        return pageTypesList;
    }
}