简体   繁体   English

公共实例变量访问错误:“非静态字段,方法或属性需要对象引用......”

[英]Public instance variable access error: “An object reference is required for the non-static field, method, or property…”

RESOLVED: Dev Env issue. 决议:Dev Env问题。 Restarted Dev Env and all OK. 重新启动Dev Env,一切正常。

First time asking, so please let me know if I'm doing this wrong. 第一次询问,所以如果我做错了,请告诉我。

I'm trying to wrap my head around using instance specific vars in C#. 我正试图在C#中使用特定于实例的变量。 The following test code seems like it should work, but throws an error: 以下测试代码似乎应该可以工作,但会抛出错误:

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

What is the correct way to do this so that I have a public var that is unique to each instance of the class, and can set that var within a function (static or otherwise)? 这样做的正确方法是什么,以便我有一个对于每个类的实例都是唯一的公共var,并且可以在函数中设置var(静态或其他)?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AlchemyWebSocketsTest2
{
    class KHandler
    {
        public string name = "wut";
        static void KHandlerInstantiate()
        {
            name = "huh";
            Console.WriteLine("All Good.");
        }

    }
}

You need an instance of KHandler. 您需要一个KHandler实例。 Note the handler object which is an instance of the KHandler class. 请注意handler对象,它是KHandler类的一个实例。

namespace AlchemyWebSocketsTest2
{
   class KHandler
   {
     public string name = "wut";
     static void Main()
     {
        KHandler handler = new KHandler();
        handler.name = "huh";
        Console.WriteLine("All Good.");
     }

  }
}

You're trying to access a non-static member inside of a static function. 您正在尝试访问静态函数内的非静态成员。 If you declare name as public static string name = "wut"; 如果将name声明为public static string name = "wut"; , then your code should compile. ,那么你的代码应该编译。 I would suggest taking a look at static classes and methods . 我建议看看静态类和方法

You're trying to assign non static (instance) member in static (type) method. 您正在尝试在静态(类型)方法中分配非静态(实例)成员。 To assign name you have to create instance of he KHandler class 要指定名称,您必须创建他的KHandler类的实例

static void Main()
{
     var khandlerInstance = new KHandler();
     khandlerInstance.name = "huh";
     Console.WriteLine("All Good.");
}

UPD. UPD。 If you need to assign a variable for each instance through the static method, you have to pass the instance as parameter. 如果需要通过静态方法为每个实例分配变量,则必须将实例作为参数传递。

class KHandler
{
    string Name;
    public static void ChangeName(KHandler targetInstance, string newName)
    {
        targetInstance.Name = newName;
    }
}

Ok, how about a few constructors? 好吧,一些构造函数怎么样?

// a sample base class
class KBase  {
     public readonly int value;  // making it readonly means it can only be assigned to once, and that has to happen during a constructor.
     public KBase ( int startValue ) { value = startValue; }
}

class KHandler : KBase
{
    public readonly string name = "wut";

    // this is a parameterless constructor, whose implementation invokes another constructor ( the one below ) of this class
    public KHandler () : this ( "huh" ) {
    }

    // this is a 1 parameter constructor, whose implementation ensures KBase is properly initialized, and then proceeds to initialize its part of the new instance.
    public KHandler ( string val ) : base ( 3 ) { 
        name = val;
    }
}

class Test {
    static void Main()
    {
        // this next line calls the parameterless constructor I defined above
        KHandler handler = new KHandler();  

        // and this next line calls the 1 parameter constructor
        KHandler handler2 = new KHandler("something else");

        Console.WriteLine("All Good 1"+handler.name);
        Console.WriteLine("All Good 2"+handler2.name);
    }
}

I think you want the basic mechanism of constructors, which are run in slightly special environment after the new class instance is allocated and "zeroed". 我想你想要构造函数的基本机制,它们在新的类实例被分配并“归零”之后在稍微特殊的环境中运行。 The special environment is that the compiler/language ensure that all the base classes and fields are properly initialized, and, you're allowed to assign to readonly members (only) during construction. 特殊环境是编译器/语言确保正确初始化所有基类和字段,并且允许在构造期间(仅)分配给只读成员。

Constructors can call base class constructors to get those bases properly initialized; 构造函数可以调用基类构造函数来正确初始化这些基础; constructors can also invoke another constructor of the same class before they proceed. 构造函数也可以在继续之前调用同一个类的另一个构造函数。

You can have more than one constructor per class -- like in my example above. 每个类可以有多个构造函数 - 就像我上面的例子一样。 If you don't specify a constructor, then the compiler effectively inserts a blank parameterless constructor for you. 如果未指定构造函数,则编译器会为您有效地插入空白无参数构造函数。 If you don't want this behavior, then adding your own constructor (of any parameter list) cancels the automatic creation of the blank parameterless constructor by the compiler/language. 如果您不想要这种行为,那么添加您自己的构造函数(任何参数列表)将取消编译器/语言自动创建空白无参数构造函数。 (If you added your own parameterized constructor and still want the parameterless constructor too, you have to add it back yourself.) (如果你添加了自己的参数化构造函数并且仍然想要无参数构造函数,则必须自己添加它。)

The first constructor (the parameterless one) is called as a result of the first new KHandler() and the second one is called by the second new KHandler (string). 第一个构造函数(无参数构造函数)作为第一个新KHandler()的结果被调用,第二个构造函数被第二个新的KHandler(字符串)调用。

Once constructed, an object is considered ready for use. 构建后,一个对象被认为可以使用了。 Anyway, search on the general construct of constructors and you'll get more information. 无论如何,搜索构造函数的一般构造,你会得到更多的信息。

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

相关问题 错误:非静态字段,方法或属性需要对象引用 - Error: An object reference is required for the non-static field, method, or property 对象引用是必需的非静态字段,方法或属性错误 - An object reference is required non-static field, method, or property error 非静态字段,方法或属性错误需要对象引用 - An object reference is required for the non-static field, method or property error 非静态字段方法或属性需要对象引用 - an object reference is required for the non-static field method or property 非静态字段,方法或属性需要对象引用 - An object reference is required for the non-static field, method, or property 非静态字段,方法或属性需要对象引用 - object reference is required for the non-static field, method, or property 并且非静态字段、方法或属性需要 Object 引用 - And Object reference is required for the non-static field, method, or property 非静态字段、方法或属性需要 object 引用 - An object reference is required for the non-static field, method, or property 非静态字段,方法或属性需要对象引用 - An object reference is required for the non-static field, method, or property 非静态字段,方法或属性需要对象引用 - An object reference is required for the non-static field, method, or property
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM