如何在c#codecontracts中告诉外部方法永远不会返回null?

[英]How do I tell in c# codecontracts that a external method never returns null?


I have the following piece of c# code:

我有以下一段c#代码:

myClaimsIdentity.FindFirst(ClaimTypes.NameIdentifier).Value;

CodeContract knows that myClaimsIdentity is never null. But it complains that the FindFirst(string) method might return null:

CodeContract知道myClaimsIdentity永远不会为null。但它抱怨FindFirst(string)方法可能返回null:

Warning CodeContracts: Possibly calling a method on a null reference. Do you expect that System.Security.Claims.ClaimsIdentity.FindFirst(System.String) returns non-null?

警告CodeContracts:可能在空引用上调用方法。您是否期望System.Security.Claims.ClaimsIdentity.FindFirst(System.String)返回非null?

I do expect this, but how can I tell it to the CodeChecker? Of course I can't change the the FindFirst(string) since it comes from an external library.

我确实希望如此,但我怎么能告诉CodeChecker?当然我不能更改FindFirst(字符串),因为它来自外部库。

1 个解决方案

#1


The simple approach is:

简单的方法是:

var nameIdentifier = myClaimsIdentity.FindFirst(ClaimTypes.NameIdentifier);
Contract.Assume(nameIdentifier != null);
nameIdentifier.Value;

Code contracts will not try to prove the Assume condition, but will use it when proving other requirements.

代码合同不会试图证明Assume条件,但会在证明其他要求时使用它。

It's probably possible to create a contract reference assembly for the external code which has the appropriate Ensures post-conditions. The code contracts team does this for the BCL types. But I don't know how to do that.

可能可以为具有适当的Ensures后置条件的外部代码创建合同引用程序集。代码合同团队为BCL类型执行此操作。但我不知道该怎么做。

智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2015/05/11/71f0a931443b168b68e897bb2ad82a0d.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告