我有一個類「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