简体   繁体   English

我无法访问在课堂上声明的变量

[英]I cannot access the variable i declared in my class

This is my c# code 这是我的C#代码

namespace abc {
    public class def: SchedulerClient 
    {
        public string key; {}
        public static void send(string abc) 
        {
            lots of code...........
            key = string;
        }
    }    
}

I am getting an error when i try to store a string value in my variable key which i have declared as "public". 我在声明为“ public”的变量键中存储字符串值时遇到错误。

This is the error i get: 这是我得到的错误:

An object reference is required for the non-static field, method, or property 'abc .def.Dkey' 非静态字段,方法或属性'abc .def.Dkey'需要对象引用

How do i overcome this? 我该如何克服呢?

You can overcome it by making your method not static: 您可以通过使方法不是静态的来克服它:

public void send(string abc) 
{
    lots of code...........
    key = stringValue;
}

or by making the field static: 或通过将字段设为静态:

public static string key;

At any rate, I think you need to think about your design and figure out what needs to be static and what doesn't. 无论如何,我认为您需要考虑设计并弄清楚什么是静态的,哪些不是静态的。

your method is static but your key is an instance. 您的方法是静态的,但是您的键是一个实例。 you cannot access instance properties or methods in a static reference. 您不能在静态引用中访问实例属性或方法。

either make them both static or make them both non static 将它们都设为静态或将它们都设为非静态

Static members are accessible only in static methods and static method can access static members as well as non-static members. 静态成员只能在静态方法中访问,并且静态方法可以访问静态成员以及非静态成员。 Please make the change accordingly. 请相应地进行更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我无法在课程外访问变量 - I cannot access a variable outside a class 我可以全局访问DrawContext变量吗? (在我应用的任何类别中) - Can i access DrawContext variable globally? ( in any class of my app) 我无法调用方法中声明的变量 class - I can't call a variable declared in the methods class 如何访问页面中声明的变量到内部类? - How to access a variable declared in a page to a inner class? 我可以访问带有另一个变量的类变量吗? - Can I access a class variable with another variable? 为什么我不能声明具有已经声明的相同名称的变量,但是新变量超出了其他变量的范围 - Why I cannot declare the variable with same name that already declared but new variable is out of the scope of other variable 无法在此范围内声明名为“ i”的局部变量,因为它将赋予“ i”不同的含义 - Local variable named 'i' cannot be declared in this scope because it would give a different meaning to 'i' 如何在通用类中访问变量 - How do I access a variable in a generic class WPF 我无法访问我的样式中的文本块 - WPF I cannot access a textblock in my style 我为一个类声明了一个变量,并将其传递给实例化它的方法,但是原始变量仍未实例化 - I declared a variable for a class, and passed it into a method to instantiate it, but the original variable remains uninstantiated
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM