【问题标题】:Pass a method as a parameter in C# from a different class在 C# 中将方法作为参数从不同的类传递
【发布时间】:2017-05-09 09:34:23
【问题描述】:

我有一个类“A”,我想通过传递一个函数作为参数来调用另一个不同的类“B”中的方法。作为参数传递的函数在B类中。那么如果我从A类调用方法怎么办?

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

我看过这个post,但它告诉了如何通过传递另一个方法作为参数来调用主方法,但来自同一个类,而不是不同的类。

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

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);
    }
}

但是如何做到以下几点:

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;
    }
}

【问题讨论】:

  • @StevenWood 这不是重复的,在说它是重复的之前请仔细阅读我的帖子。在您说的帖子中,如果您从同一个类调用 RunTheMethod,它提供了一个解决方案,但是如果您从另一个不同的类调用 RunTheMethod 会发生什么?此外,您提供的链接是我在帖子中提供的,请参阅帖子中的链接。

标签: c# lambda delegates .net-3.5 function-pointers


【解决方案1】:

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

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

        (...)
}

【讨论】:

  • 好的,但是如果 B 类中的方法是公共的,它就可以工作,如果它们是私有的,那就不可能了,对吧?
  • 不,还有可能
  • 怎么样?例如,如果 Method1 是私有的,则从类 A 和方法 Test 你不能返回 myClass.RunTheMethod(myClass.Method1) 因为当你传递 myClass.Method1 时,这是不可见的。
  • 也许this 可以帮忙?
【解决方案2】:

试试这个

public Class A
{
        (...)

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

        (...)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-09
    • 1970-01-01
    • 1970-01-01
    • 2021-02-05
    • 1970-01-01
    • 2022-01-10
    相关资源
    最近更新 更多