我如何将可空值传递给方法
[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();
}
}
由于
答案 0 :(得分:1)
异常是{null}时使用obj
的某些方法或属性的结果。你必须检查它是否为你自己的
void DoWork(ISomeInterface obj) //Not working
{
if(obj == null)
{
return;
}
/* do something ... */}
}
答案 1 :(得分:0)
这里假设当你启动异步下载时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();
}
答案 2 :(得分:-2)
这可以通过放置一个?在函数头中的对象类型之后。
void DoWork(ISomeInterface? obj)