您还必须将要调用的委托或方法的名称作为字符串存储在类中。
我使用它是因为我想在配置文件中配置通过ftp下载文件后要调用的函数,即不同的ftp下载配置通过调用配置的方法(委托)以不同的方式处理下载的文件。
public delegate string ProcessDownloadedFile(string filename);
//HACK: Cannot serialise delegates.
public string ProcessDownloadFileMethod { get; set; }
//HACK: Cannot serialise delegates.
[XmlIgnore]
public ProcessDownloadedFile ProcessFile { get; set; }
然后当你想使用委托时,在这种情况下,我已经下载了文件。我使用存储在序列化配置文件中的字符串创建委托。
//Create the delegate method if it has been set.
if (!String.IsNullOrEmpty(ftpReceive.ProcessDownloadFileMethod) && ftpReceive.ProcessFile == null)
{
//Create the delegate.
Type t = typeof(FTPTransfer);
ftpReceive.ProcessFile = (FTPTransfer.ProcessDownloadedFile) Delegate.CreateDelegate(typeof(FTPTransfer.ProcessDownloadedFile), t.GetMethod(ftpReceive.ProcessDownloadFileMethod));
}
因此,理想情况下,您希望将要调用的函数/委托的名称存储为字符串,然后在运行时使用反射从字符串中创建它。
希望这会有所帮助。
或者,如果要调用的方法只存在于一个类中,您可以通过包装属性来简化它。
//HACK: Cannot serialise delegates.
public string ProcessDownloadFileMethod { get; set; }
//HACK: Cannot serialise delegates.
private ProcessDownloadedFile _processFile;
[XmlIgnore]
public ProcessDownloadedFile ProcessFile
{
get
{
if (_processFile == null && !String.IsNullOrEmpty(ProcessDownloadFileMethod))
{
Type t = this.GetType();
this._processFile = (ProcessDownloadedFile) Delegate.CreateDelegate(typeof(ProcessDownloadedFile), t.GetMethod(this.ProcessDownloadFileMethod));
}
return _processFile;
}
set
{
if (value != null)
{
ProcessDownloadFileMethod = value.Method.Name;
} else {
ProcessDownloadFileMethod = null;
}
_processFile = value;
}
}
要真正做到这一点,最好包含类/类型以及用于创建委托的函数/方法名称。