接口中的非静态字段,方法或属性需要对象引用 [英] An object reference is required for the non-static field, method, or property in interfaces

查看:79
本文介绍了接口中的非静态字段,方法或属性需要对象引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  class 程序:abc 
{
static void Main( string [] args)
{
Console。 WriteLine( hello interface);

xyz();

Console.ReadLine();
return ;
}
public void xyz()
{
Console.WriteLine( interface XYZ);
}
}
interface abc
{
void xyz();
}

解决方案

您正试图直接访问实例成员到您的 Main()不使用对象,这是不正确的。您必须首先创建一个对象,然后使用其方法,如下一个示例所示:

 abc testObject =  new 程序();  //  该对象被声明为接口abc,但也可以声明为Program类型! 
testObject.xyz();


您评论中的代码段现在是正确的。您需要了解实例成员与公共成员的对象,this参数的作用以及理解其背后的一般面向对象语法和语义(不,这还不是OOP,只是先决条件之一)。请查看我过去的答案:

在c#中输入类型 [ ^ ] ,

C# windows基于这个关键词及其在应用程序中的用途 [ ^ ],

是什么让静态方法可以访问? [ ^ ]。



-SA

class Program: abc
    {
        static void Main(string[] args)
        {
            Console.WriteLine("hello interface");

            xyz();

            Console.ReadLine();
            return;
        }
        public void xyz()
        {
            Console.WriteLine("interface XYZ");
        }
    }
    interface abc
    {
        void xyz();
    }

解决方案

You are trying to access an instance member directly into your Main() without to use an object, and this in incorrect. You must first create an object then use its method like in the next example:

abc testObject = new Program(); //The object is declared as interface "abc" but could be also declared of type "Program"!
testObject.xyz();


Your piece of code in your comment is now correct. You need to learn what are instance members vs public ones, the role of "this" parameter and understand general object-oriented syntax and semantic behind it (no, this is not yet OOP, just one of the prerequisites). Please see my past answers:
Type casting in c#[^],
C# windows base this key word related and its uses in the application[^],
What makes static methods accessible?[^].

—SA


这篇关于接口中的非静态字段,方法或属性需要对象引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆