为什么我的代表程序给我一个错误?

时间:2014-08-22 06:27:36

标签: c# delegates

我试过这个程序,它工作正常。

class MyProgram
{
    delegate string StrMode(string s);

    static string ReplaceSpace(string s)
    {
        return s.Replace(' ', '-');
    }
    static void Main()
    {
        Console.WriteLine("This is a Method Group Conversion example.");

        StrMode sm = ReplaceSpace;
        string str1 = sm("This is a test.");
        Console.WriteLine(str1);
    }
}

上面的程序给了我最好的输出,但我想要创建一些新的东西,两个类可以倾向于使用委托方法调用,就像我在程序下面做的那样但是这让我SICK并且让我不应该调用错误,请帮助,我想用两个班级来代表队员,那可能吗?

delegate string StrMod(string s);

public class MyProgram1
{
    public static string ReverseString(string s)
    {
        string temp = "";
        int i, j;
        for (j = 0, i = s.Length - 1; i >= 0; i--, j++)            
            temp = temp + s[i];

        return temp;
    }
}

public class MyProgram2
{
    public static string RemoveSpace(string s)
    {
        string temp = "";
        for (int i = 0; i < s.Length; i++)            
            if (s[i] != ' ')
                temp = temp + s[i];

        return temp;
    }
}

class MainProgram
{
    public static void Main(string[] args)
    {
        //creating an object for class 1..
        MyProgram1 mp1 = new MyProgram1();
        string str;

        StrMod str = mp1.ReverseString;
        string str2 = str("This is test.");
        Console.WriteLine(str2);
    }
}

被修改

这是我的错误:

enter image description here

1 个答案:

答案 0 :(得分:1)

您已经定义了名为str的本地变量。您不能为委托变量使用相同的名称:

string str; // first definition    
StrMod str = mp1.ReverseString; // same name (also another issue - see below)

更改问题后,错误原因是您的ReverseString方法是静态的,但您将其用作实例方法。您不需要创建和使用MyProgram1类的实例。您应该使用类名来访问静态成员:

StrMod str = MyProgram1.ReverseString;

BTW错误消息非常具有自我描述性:

  

会员&#39; MyProgram1.ReverseString(字符串)&#39;无法访问   实例参考;使用类型名称来限定它

它甚至暗示你应该怎么做才能修复错误。

相关问题