我有一个类“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;
}
}
的可能的复制[通行证方法参数使用C#(http://stackoverflow.com/questions/2082615/pass-method-as-parameter-using-c-sharp) –
@ StevenWood它不是重复的,请在说它是重复的之前先阅读我的文章。在你说的帖子中,如果你从同一个班级调用RunTheMethod,它会提供一个解决方案,但是如果你从另一个班级调用RunTheMethod,会发生什么?此外,您提供的链接已由我在帖子中提供,请参阅帖子中的链接。 – user1624552