将方法作为参数从其他类传递到C#

将方法作为参数从其他类传递到C#,c#,lambda,delegates,.net-3.5,function-pointers,C#,Lambda,Delegates,.net 3.5,Function Pointers,我有一个类“a”,我想从中调用另一个不同类“B”中的方法,方法是将函数作为参数传递。作为参数传递的函数在类B中。所以,如果我从类a调用方法,该如何做呢 我正在使用Visual Studio 2008和.NET Framework 3.5 我已经看到了这一点,但它告诉我们如何通过将另一个方法作为参数传递给main方法,但该方法来自同一个类,而不是不同的类 例如,在该帖子中提供了以下示例: public class Class1 { public int Method1(string inp

我有一个类“a”,我想从中调用另一个不同类“B”中的方法,方法是将函数作为参数传递。作为参数传递的函数在类B中。所以,如果我从类a调用方法,该如何做呢

我正在使用Visual Studio 2008和.NET Framework 3.5

我已经看到了这一点,但它告诉我们如何通过将另一个方法作为参数传递给main方法,但该方法来自同一个类,而不是不同的类

例如,在该帖子中提供了以下示例:

public class Class1
{
    public int Method1(string input)
    {
        //... do something
        return 0;
    }

    public int Method2(string input)
    {
        //... do something different
        return 1;
    }

    public bool RunTheMethod(Func<string, int> myMethodName)
    {
        //... do stuff
        int i = myMethodName("My String");
        //... do more stuff
        return true;
    }

    public bool Test()
    {
        return RunTheMethod(Method1);
    }
}
公共类1
{
公共int方法1(字符串输入)
{
//…做点什么
返回0;
}
公共int方法2(字符串输入)
{
//…做点不同的事
返回1;
}
公共bool运行方法(Func myMethodName)
{
//…做事
int i=myMethodName(“我的字符串”);
//…做更多的事情
返回true;
}
公共布尔测试()
{
返回运行方法(方法1);
}
}
但如何做到以下几点:

public Class A
{
        (...)

        public bool Test()
        {
            return RunTheMethod(Method1);
        }

        (...)
}


public class B
{
    public int Method1(string input)
    {
        //... do something
        return 0;
    }

    public int Method2(string input)
    {
        //... do something different
        return 1;
    }

    public bool RunTheMethod(Func<string, int> myMethodName)
    {
        //... do stuff
        int i = myMethodName("My String");
        //... do more stuff
        return true;
    }
}
公共A类
{
(...)
公共布尔测试()
{
返回运行方法(方法1);
}
(...)
}
公共B级
{
公共int方法1(字符串输入)
{
//…做点什么
返回0;
}
公共int方法2(字符串输入)
{
//…做点不同的事
返回1;
}
公共bool运行方法(Func myMethodName)
{
//…做事
int i=myMethodName(“我的字符串”);
//…做更多的事情
返回true;
}
}
试试这个

public Class A
{
        (...)

        public bool Test()
        {
            var b = new B();
            return b.RunTheMethod(b.Method1);
        }

        (...)
}

您需要在
class A
内部创建
class B
的实例,然后调用该方法,例如,将
class A
更改为:

public Class A
{
        (...)
        private B myClass = new B();
        public bool Test()
        {
            return myClass.RunTheMethod(myClass.Method1);
        }

        (...)
}

可能重复的@StevenWood它不是重复的,请仔细阅读我的帖子,然后再说它是重复的。在你的帖子中说,如果你从同一个类调用RunTheMethod,它提供了一个解决方案,但是如果你从另一个不同的类调用RunTheMethod,会发生什么呢?此外,您提供的链接已经由我在帖子中提供了,请参阅帖子中的链接。好的,但是如果类B中的方法是公共的,那么它是有效的,如果它们是私有的,那么它是不可能的,对吗?不,它仍然可能如何?例如,如果Method1是私有的,那么从类A和方法测试中,您不能返回myClass.RunTheMethod(myClass.Method1),因为当您传递myClass.Method1时,它是不可见的。可能可以帮助您吗?