C# 为什么我的代理程序给我一个错误?

C# 为什么我的代理程序给我一个错误?,c#,delegates,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

我试过这个程序,效果很好

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);
    }
}
上面的程序给了我最好的输出,但我想做一些新的东西,两个类可以像我在程序下面做的那样,使用委托方法调用,但是这让我感到恶心,并且让我对调用错误感到不友好,请帮助,我想使用两个类来扮演委托,这可能吗

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);
    }
}
委托字符串StrMod(字符串s);
公共类MyProgram1
{
公共静态字符串反向限制(字符串s)
{
字符串temp=“”;
int i,j;
对于(j=0,i=s.长度-1;i>=0;i--,j++)
温度=温度+s[i];
返回温度;
}
}
公共类MyProgram2
{
公共静态字符串RemoveSpace(字符串s)
{
字符串temp=“”;
对于(int i=0;i
已编辑

这是我的错误:


您已经用名称
str
定义了局部变量。不能对委托变量使用相同的名称:

string str; // first definition    
StrMod str = mp1.ReverseString; // same name (also another issue - see below)
更改问题后,错误的原因是
ReverseString
方法是静态的,但您将其用作实例方法。您不需要创建和使用
MyProgram1
类的实例。应使用类名访问静态成员:

StrMod str = MyProgram1.ReverseString;

顺便说一句,错误消息是非常自我描述的:

无法使用访问权限访问成员“MyProgram1.ReverseString(字符串)” 实例引用;改为使用类型名称限定它


它甚至提示您应该如何修复错误。

错误是什么?另外,请添加缩进请花些时间改进代码的格式谢谢,但你能帮我吗,我相信编码逻辑,但不相信格式。。抱歉,但别误会我:)@mehirmehta:如果你不能费心以可读的格式呈现代码,为什么要有人费心来帮助你?你的代码很难阅读,因此你的文章很难阅读,因此人们会继续问一个问题,问这个问题的人实际上尊重那些试图帮助你的人的时间。此外,如果你有错误,你应该说他们是什么。“给我不友善的调用错误”还不够详细。没错——虽然这不是唯一的问题。@JonSkeet谢谢Jon,更新。使用原始格式很难看到任何东西:)
用一个类型名来限定它,这让我恶心!!…:p@mehirmehta这就是静态成员的使用方式。这是为类型定义的成员,而不是为类型的某个特定实例定义的成员。对不起,我在每个方法中都使用了
静态
,正如您在我的代码中看到的那样,man:)