开发者

Passing nullable value to a method

How i can pass nullable value to a method

[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)
  开发者_如何学JAVA      {
            //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();
        }

}

Thanks


Exception is result of using some method or property of the obj when its null. You have to check if its null on your own

void DoWork(ISomeInterface obj) //Not working
{
    if(obj == null)
    {
        return;
    }
    /* do something ... */}
}


Here you are assuming that obj is null when you start the async download, and that someway it's no more null when DownloadCompleted is triggered. Is there something that you didn't show that guarantee you this condition is satisfied? What are you doing after DownloadAsync, and how can you be sure that this will be evaluated before the completion of the download?

    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();
    }


This can be achieved by placing a ? after the object type in your function header.

void DoWork(ISomeInterface? obj)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜