Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# &引用;成员';Class1.GetChar(字符串,int)和#x27;无法使用实例引用访问_C#_.net - Fatal编程技术网

C# &引用;成员';Class1.GetChar(字符串,int)和#x27;无法使用实例引用访问

C# &引用;成员';Class1.GetChar(字符串,int)和#x27;无法使用实例引用访问,c#,.net,C#,.net,我想返回表示所提供字符串中指定索引中的字符的Char值。但是发生了错误 我已经在VisualStudio上试过了 namespace ConsoleApp1 { class Class1 { public static char GetChar(string str, int a) { return str[a]; } } } namespace ConsoleApp1 {

我想返回表示所提供字符串中指定索引中的字符的Char值。但是发生了错误

我已经在VisualStudio上试过了

namespace ConsoleApp1
{
    class Class1
    {
        public static char GetChar(string str, int a)
        {
            return str[a];
                }
    }
}


namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Class1 class1 = new Class1();
            var result = class1.GetChar("abcdef", 4);
            Console.Read();
        }
    }
}

当我尝试使用该函数时,它显示错误:“无法使用实例引用访问成员'Class1.GetChar(string,int)';请改为使用类型名对其进行限定。”我不知道如何调整。

在方法'GetChar'上,您有静态修饰符。 这意味着Class1的实例不使用该方法,而只使用Class1本身

因此,您必须通过说Class1.GetChar(“abcdef”,4)来调用这个方法,您不能用Class1的实例调用这个方法

为了进一步说明,您的错误是:“Class1.GetChar(string,int)”不能通过实例引用访问;请改为使用类型名限定它。”

您创建的变量(class1)是class1实例。 Class1是一种类型。
因此,当它说“改为使用类型名限定它”时,它意味着您必须使用类型名(Class1)而不是所需类型的实例。

GetChar
是一个
静态方法,应该针对类型(
Class1.GetChar(…)
)调用。@Siren为什么您希望它显示任何内容?你什么都没写
return
表示该方法向调用方返回一个值。在您的情况下,此值存储在
result
中。你哪里也写不出来。尝试
Console.WriteLine(结果)@John谢谢!!我刚刚找到了方法并删除了我之前的评论,当然,另一个解决方案是使该方法非静态,以便可以用实例调用它。