日期:2014-05-20  浏览次数:20875 次

C#根据配置文件动态执行函数的问题
在一个类里有很多方法(函数),主程序执行时会根据配置文件的内容执行其中的
某一个函数,需要时会修改配置文件让程序调用其他函数,主程序不用修改或编译。
该如何实现?
C#2005   +   Win2003
配置文件:
<?xml   version= "1.0 "   standalone= "yes "?>
<DocumentElement>
    <MethodrInfo>
        <MethodName> Post2013 </MethodName>     //该行可以经常修改
    </MethodrInfo>
</DocumentElement>

------解决方案--------------------
请使用反射
------解决方案--------------------
--xml
<?xml version= "1.0 " encoding= "utf-8 " ?>
<configuration>
<appSettings>
<add key= "mp3 " value= "Wayfarer.MediaLibrary.MP3MediaFactory "/>
<add key= "wav " value= "Wayfarer.MediaLibrary.WavMediaFactory "/>
<add key= "rm " value= "Wayfarer.MediaLibrary.RMMediaFactory "/>
<add key= "mpeg " value= "Wayfarer.MediaLibrary.MpegMediaFactory "/>
</appSettings>
</configuration>

--code

string mediaTypeKey = cbbMediaType.SelectedItem.ToString().ToLower();--类型


string mediaTypeValue = ConfigurationSettings.AppSettings[mediaTypeKey].ToString();
IMediaFactory iFactory = (IMediaFactory)Activator.CreateInstance( "Wayfarer.MediaLibrary ",mediaTypeValue).Unwrap();

IMedia iMedia = iFactory.CreateMedia();
iMedia.Play();
------解决方案--------------------
在config中的AppConfig中定义,然后程序中读取出来,在
if(。。){
}
else if(..)
{
}
...
else
{
}
------解决方案--------------------
楼上两位正解!
只要在源代码中加入判断条件,根据从配置文件中读入的数据来决定具体执行哪个函数即可。
------解决方案--------------------
反射更灵活一些