我有一个问题,我不知道如何攻击。希望有人能把我踢向正确的方向。=)
我已经创建了几个类,即Word、Excel、Microstation。在这些类中,我有相同名称的相同函数,它们做相同的事情(当然,使用不同的代码)。
程序(Excel附加模块)的输入是一个文件,可以是Word、Excel或Microstation。根据文件类型,我会创建正确类(Word、Excel或Microstation)的实例。
创建实例后,我想调用一个函数,该函数将调用实例化的类函数。
我想这样做:
public function RunTheFunctions(??? o)
{
o.OpenFile();
o.DoStuff();
o.SaveFile();
}而不是:
oWord.OpenFile();
oWord.DoStuff();
oWord.SaveFile();
oExcel.OpenFile();
oExcel.DoStuff();
oExcel.SaveFile();
oMicrostation.OpenFile();
oMicrostation.DoStuff();
oMicrostation.SaveFile();我试过了:
object o;
Word oWord = new Word();
o = oWord;
o.OpenFile();但它不起作用。
我希望我的问题是比较清楚的。=)
致敬,S
发布于 2013-04-20 21:36:31
您可以创建由Word、Excel、Microstation类实现的接口:
// interface for your document classes
interface IDocument
{
void OpenFile();
void DoStuff();
void SaveFile();
}
// Word implements IDocument
class Word : IDocument
{
public void OpenFile() { /* ... */ }
public void DoStuff() { /* ... */ }
public void SaveFile() { /* ... */ }
}
// later
public function RunTheFunctions(IDocument o)
{
o.OpenFile();
o.DoStuff();
o.SaveFile();
}
// usage
IDocument doc = new Word();
RunTheFunctions(doc);发布于 2013-04-20 21:36:11
使用所需的方法创建一个接口,并在具体的类中实现它:
public interface IDocument
{
void OpenFile();
void DoStuff();
void SaveFile();
}
public class Word : IDocument { .... }
public function RunTheFunctions(IDocument o)
{
o.OpenFile();
o.DoStuff();
o.SaveFile();
}发布于 2013-04-20 21:44:29
除了接口解决方案,这是正确的方式,你也可以使用dynamic作为参数类型,如果.NET框架>= 4.0.如果Word、Excel和Microstation是第三方类,并且不共享公共接口或基类,则此解决方案是有意义的。(实际上你可以在这种情况下使用Adapter Pattern,并返回到界面解决方案)
public void RunTheFunctions(dynamic o)
{
o.OpenFile();
o.DoStuff();
o.SaveFile();
}如果提供的对象没有相应的方法,这将在运行时抛出异常。
https://stackoverflow.com/questions/16120941
复制相似问题