2017-05-09 84 views
-1

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

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

我已经看到这个post,但它告诉我们如何通过传递另一个方法作为参数,但是来自同一个类而不是不同的类来调用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); 
    } 
} 

但如何做到以下几点:

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

的可能的复制[通行证方法参数使用C#(http://stackoverflow.com/questions/2082615/pass-method-as-parameter-using-c-sharp) –

+0

@ StevenWood它不是重复的,请在说它是重复的之前先阅读我的文章。在你说的帖子中,如果你从同一个班级调用RunTheMethod,它会提供一个解决方案,但是如果你从另一个班级调用RunTheMethod,会发生什么?此外,您提供的链接已由我在帖子中提供,请参阅帖子中的链接。 – user1624552

回答

1

你需要做在class A里面的一个class B的实例然后调用该方法,例如,改变您class A到:

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

     (...) 
} 
+0

好的,但它适用于B类中的方法是公共的,如果它们是私人的,这是不可能的,对吧? – user1624552

+0

不,它仍然有可能 – Hristo

+0

怎么样?如果例如Method1是私有的,则从类A和方法Test你不能返回myClass.RunTheMethod(myClass.Method1),因为当你传递myClass.Method1时,这是不可见的。 – user1624552

1

试试这个

public Class A 
{ 
     (...) 

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

     (...) 
}