将可为空的值传递给方法
本文关键字:方法 值传 | 更新日期: 2023-09-27 18:07:17
如何将可空值传递给方法
[Import("Default", typeof(ISomeInterface), AllowRecomposition = true, AllowDefault = true)]
public ISomeInterface x { get; set; }
// x is null till now
void DoWork(ISomeInterface obj) //Not working
{
if (obj == null)
{
//Download and Satisfy
DeploymentCatalog DC = new DeploymentCatalog("TheXAPfile.xap");
DC.DownloadCompleted += (s, e) =>
{
catalog.Catalogs.Add(f); //catalog is AggregateCatalog
obj.Show();
};
DC.DownloadAsync();
}
else
{
obj.Show();
}
}
谢谢
异常是在obj
为空时使用某些方法或属性的结果。你必须自己检查它是否为空
void DoWork(ISomeInterface obj) //Not working
{
if(obj == null)
{
return;
}
/* do something ... */}
}
在这里你假设当你开始异步下载时obj是null,并且当DownloadCompleted被触发时它不再是null。有没有什么你没有证明的东西可以保证你满足这个条件?你在DownloadAsync之后做什么,你怎么能确保这将在下载完成之前进行评估?
if (obj == null)
{
//// you enter here only if obj is null
//Download and Satisfy
DeploymentCatalog DC = new DeploymentCatalog("TheXAPfile.xap");
DC.DownloadCompleted += (s, e) =>
{
catalog.Catalogs.Add(f); //catalog is AggregateCatalog
//// here you are assuming that obj is not null anymore. Why???
obj.Show();
};
DC.DownloadAsync();
}
这可以通过放置?在函数头的对象类型之后。
void DoWork(ISomeInterface? obj)