Error cs0176 member

I am getting into C# and I am having this issue: namespace MyDataLayer { namespace Section1 { public class MyClass { public class MyItem { ...

Check whether your code contains a namespace which the right most part matches your static class name.

Given the a static Bar class, defined on namespace Foo, implementing a method Jump or a property, chances are you are receiving compiler error because there is also another namespace ending on Bar. Yep, fishi stuff ;-)

If that’s so, it means your using a Using Bar; and a Bar.Jump() call, therefore one of the following solutions should fit your needs:

  • Fully qualify static class name with according namepace, which result on Foo.Bar.Jump() declaration. You will also need to remove Using Bar; statement
  • Rename namespace Bar by a diffente name.

In my case, the foollowing compiler error occurred on a EF (Entity Framework) repository project on an Database.SetInitializer() call:

Member 'Database.SetInitializer<MyDatabaseContext>(IDatabaseInitializer<MyDatabaseContext>)' cannot be accessed with an instance reference; qualify it with a type name instead MyProject.ORM

This error arouse when I added a MyProject.ORM.Database namespace, which sufix (Database), as you might noticed, matches Database.SetInitializer class name.

In this, since I have no control on EF’s Database static class and I would also like to preserve my custom namespace, I decided fully qualify EF’s Database static class with its namepace System.Data.Entity, which resulted on using the following command, which compilation succeed:

System.Data.Entity.Database.SetInitializer<MyDatabaseContext>(MyMigrationStrategy)

Hope it helps

Permalink

Cannot retrieve contributors at this time

description title ms.date f1_keywords helpviewer_keywords ms.assetid

Compiler Error CS0176

Compiler Error CS0176

07/20/2015

CS0176

CS0176

783c13d8-5ac3-4aeb-bd63-0468cb05550d

Compiler Error CS0176

Static member ‘member’ cannot be accessed with an instance reference; qualify it with a type name instead

Only a class name can be used to qualify a static variable; an instance name cannot be a qualifier. For more information, see Static Classes and Static Class Members.

The following sample generates CS0176:

// CS0176.cs  
public class MyClass2  
{  
    public static int num;  
}  
  
public class Test  
{  
    public static void Main()  
    {  
        MyClass2 mc2 = new MyClass2();  
        int i = mc2.num;   // CS0176  
        // try the following line instead  
        // int i = MyClass2.num;  
    }  
}  

C# Compiler Error

CS0176 – Static member ‘member’ cannot be accessed with an instance reference; qualify it with a type name instead

Reason for the Error

You will receive this error when you try to access a static variable of a class with an instance as a qualifier.

For example, try compiling the below code snippet

namespace DeveloperPubNamespace
{
    public class Employee
    {
        public static int EmployeeCount = 0;
    }

    class Program
    {
        static void Main(string[] args)
        {
            Employee emp = new Employee();
            emp.EmployeeCount=1;
        }
    }
}

The above code snippet will result with the error code CS0176

Error CS0176 Member ‘Employee.EmployeeCount’ cannot be accessed with an instance reference; qualify it with a type name instead ConsoleApp3 C:UsersSenthilsourcereposConsoleApp3ConsoleApp3Program.cs 13 Active

Solution

To fix this error, ensure that you access the static variable directly using the class name instead of the instance name as the qualifier. The above code snippet can be fixed by replacing the Main() function with the below code snippet.

static void Main(string[] args)
{
	Employee.EmployeeCount=1;
}

Maksim1307

2 / 2 / 0

Регистрация: 04.11.2020

Сообщений: 220

1

10.11.2020, 20:00. Показов 1794. Ответов 2

Метки error, script, unity, unity 2d, unity 3d, unity engine, unity script c# (Все метки)


Вылезает вот такая ошибка:
error CS0176: Member ‘myClass.Position’ cannot be accessed with an instance reference; qualify it with a type name instead
Вот часть кода:

C#
1
2
3
4
5
6
7
8
9
10
public static Dictionary<Vector2, myClass> MyDictionary = new Dictionary<Vector2, myClass>();
public static List <Vector2> toGenerate;
//[...]
Vector2 cp = new Vector2(toGenerate[0].x, toGenerate[0].y);
      if(!MyDictionary.ContainsKey(cp)){
           MyDictionary.Add(cp, new myClass());
           MyDictionary[cp].Position = cp;           //<-- ошибка тут
           MyDictionary[cp].Generation();
           MyDictionary[cp].Optimization();
       }

Вот часть кода myClass:

C#
1
2
3
4
5
6
7
8
[System.Serializable]
//[...]
public class myClass : MonoBehaviour
{
    public static Vector2 Position;
    public Vector3 Position3D = new Vector3(Position.x, 0, Position.y);
    //[...]
}

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



2496 / 1512 / 803

Регистрация: 23.02.2019

Сообщений: 3,689

10.11.2020, 20:54

2

Ваше поле Position является статичным, а статичные члены принадлежат классу, а не экземплярам класса.

Maksim1307, скорее всего вы делаете какую-то игру и вот такие «непонятные» ошибки скорее всего очень вам неприятны, правда? Попробуйте пока отложить на пару недель Unity и просто пройтись по основам языка C#. Даже если это займёт довольно много времени, оно того стОит. По вашим ошибкам видно (уже в нескольких темах), что вам ещё не хватает знаний по базе самого языка программирования.



0



2 / 2 / 0

Регистрация: 04.11.2020

Сообщений: 220

16.11.2020, 18:51

 [ТС]

3

Когда я спрашивал на другом форуме, какие книги по unity нужно почитать, мне сказали, что лучше учиться на практике, так что остался открытым вопрос: где можно изучить c# под Unity на хорошем уровне? Есть ли хорошие книги, видеоуроки или курсы по c# и Unity на русском или хотя бы на немецком? Все, которые я нашел написаны на английском или уже не актуальны



0



error CS0176: Static member NetworkPeerType.Disconnected

Здравствуйте! Столкнулся с ошибкой который раньше не было при тех же условиях. Подскажите. Толи просит её Static сделать. Толи доступа нет. Ничего не понимаю. :-?

Assets/Test1.cs(12,43): error CS0176: Static member `UnityEngine.NetworkPeerType.Disconnected’ cannot be accessed with an instance reference, qualify it with a type name instead

Используется csharp

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Test1 : MonoBehaviour {

        string msg = «Click to Start»;

        void OnGUI(){
                msg = GUI.TextField(new Rect(10,10,300,20),msg);

                if(Network.peerType == Network.peerType.Disconnected){
                        if(GUI.Button(new Rect(10,35,100,30),«Start»)){
                                Network.InitializeServer(10,25000,false);
                        }
                }

                if(Network.peerType != Network.peerType.Disconnected){
                        msg= «Server OK!»;
                        if(GUI.Button(new Rect(10,35,100,30),«Off»)){
                                Network.Disconnect();
                                msg= «Click to   start»;
                        }
                }

        }
}

Скрин проекта:

Аватара пользователя
rc2f6
UNIт
 
Сообщения: 120
Зарегистрирован: 05 окт 2009, 20:19


Re: error CS0176: Static member NetworkPeerType.Disconnected

Сообщение rc2f6 09 авг 2017, 16:03

Anonymyx писал(а):https://docs.unity3d.com/ScriptReference/Network-peerType.html
Это называется «перечисление».

Используется csharp

if(Network.peerType == NetworkPeerType.Disconnected){

PS. Надеюсь вы знаете что значит «deprecated».

Спасибо! Не заметил точку. Сказывается то что долго не садился за код. :D/ Всё меняется с каждой версией. А я даже не думал что есть изменения. :ympeace:

Изображение

Аватара пользователя
rc2f6
UNIт
 
Сообщения: 120
Зарегистрирован: 05 окт 2009, 20:19


Вернуться в Скрипты

Кто сейчас на конференции

Сейчас этот форум просматривают: Google [Bot] и гости: 6



Понравилась статья? Поделить с друзьями:
  • Error cs0165 use of unassigned local variable
  • Error cs0161 not all code paths return a value
  • Error cs0150 a constant value is expected
  • Error cs0149 требуется имя метода
  • Error cs0149 method name expected