Member '' cannot be accessed with an instance reference

前端 未结 10 1695
我在风中等你
我在风中等你 2020-11-22 10:39

I am getting into C# and I am having this issue:

namespace MyDataLayer
{
    namespace Section1
    {
        public class MyClass
        {
            publ         


        
相关标签:
10条回答
  • 2020-11-22 11:17
    YourClassName.YourStaticFieldName
    

    For your static field would look like:

    public class StaticExample 
    {
       public static double Pi = 3.14;
    }
    

    From another class, you can access the staic field as follows:

        class Program
        {
         static void Main(string[] args)
         {
             double radius = 6;
             double areaOfCircle = 0;
    
             areaOfCircle = StaticExample.Pi * radius * radius;
             Console.WriteLine("Area = "+areaOfCircle);
    
             Console.ReadKey();
         }
      }
    
    0 讨论(0)
  • 2020-11-22 11:19

    You can only access static members using the name of the type.

    Therefore, you need to either write,

    MyClass.MyItem.Property1
    

    Or (this is probably what you need to do) make Property1 an instance property by removing the static keyword from its definition.

    Static properties are shared between all instances of their class, so that they only have one value. The way it's defined now, there is no point in making any instances of your MyItem class.

    0 讨论(0)
  • 2020-11-22 11:21

    In C#, unlike VB.NET and Java, you can't access static members with instance syntax. You should do:

    MyClass.MyItem.Property1
    

    to refer to that property or remove the static modifier from Property1 (which is what you probably want to do). For a conceptual idea about what static is, see my other answer.

    0 讨论(0)
  • 2020-11-22 11:22

    This causes the error:

    MyClass aCoolObj = new MyClass();
    aCoolObj.MyCoolStaticMethod();
    

    This is the fix:

    MyClass.MyCoolStaticMethod();
    

    Explanation:

    You can't call a static method from an instance of an object. The whole point of static methods is to not be tied to instances of objects, but instead to persist through all instances of that object, and/or to be used without any instances of the object.

    0 讨论(0)
提交回复
热议问题