【问题标题】:c# Methods error CS0236 [duplicate]c#方法错误CS0236 [重复]
【发布时间】:2017-04-04 15:31:09
【问题描述】:

伙计们,我需要一些帮助, 我有错误 第 50 行:CS0236 C# 字段初始化程序无法引用非静态字段、方法或属性 第 51 行:CS0236 C# 字段初始化程序无法引用非静态字段、方法或属性

namespace ConsoleApplication5
{
    public delegate string Metodo(string t1, string t2);

    class Program
    {
        static void Main(string[] args)
        {

        }
    }

    public class ExemploDel
    {
        public static string NomeMetodo(string t1, string t2)
        {
            return t1 + t2;
        }

        Metodo meuMetodo = NomeMetodo;
    }

    public class Metodos
    {

        public string Method1(string tx1, string tx2)
        {
            return tx1 + tx2;
        }
        public string Method2(string tx1, string tx2)
        {
            return tx2 + tx1;
        }
    }

    public class DelegatesEx
    {
        public static string NomeMetodo(string t1, string t2)
        {
            return t1 + t2;
        }

        Metodos obj = new Metodos();
        Metodo m1 = obj.Method1;
        Metodo m2 = obj.Method2;
        Metodo m3 = NomeMetodo;

    }
}

【问题讨论】:

  • 您是否阅读了错误信息?这很清楚。如果你还是不明白,你试过谷歌搜索吗?这个错误非常常见。给您一些一般性的指示:您在 DelegatesEx 中 NomeMetodo 之后的代码不在方法内。您还可以像引用属性一样引用方法。

标签: c#


【解决方案1】:

首先,你把调用代码放错地方了,你程序的Main方法中应该有以下4行:

解决方案1:

class Program
{
    static void Main(string[] args)
    {
       Metodos obj = new Metodos();
       Metodo m1 = obj.Method1;
       Metodo m2 = obj.Method2;
       Metodo m3 = NomeMetodo;
    }
}

其次,当您尝试为其分配实例方法时,您已将委托标记为static,因此请在声明中将委托设为非静态并将方法设为静态。

public delegate string Metodo(string t1, string t2);

解决方案2:

如果您想让Metodo 委托保持静态,那么您的方法也应该是静态的,例如:

public class Metodos
{

        public static string Method1(string tx1, string tx2)
        {
            return tx1 + tx2;
        }
        public static string Method2(string tx1, string tx2)
        {
            return tx2 + tx1;
        }
}

现在你的主要方法代码也将被改变,因为静态方法是使用类而不是它的实例来访问的:

class Program
{
    static void Main(string[] args)
    {
       Metodo m1 = Metodos .Method1;
       Metodo m2 = Metodos .Method2;
       Metodo m3 = NomeMetodo;
    }
}

【讨论】:

    猜你喜欢
    • 2014-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-13
    • 1970-01-01
    • 2016-10-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多