I am facing a problem that I can not figure out.
Say I have two methods: public void Method1(object obj)
in ViewModel
class and public void Method2(object obj)
in Model
class.
Method2
gets called from Method1
using the instance of Model
class(say, objM is the object of Model
class and a member of ViewModel
class).
class ViewModel
{
public void Methods1(object obj)
{
if (!(
( (false == this.HasSal)
&& (typeof(Class1) == obj.GetType())
)
||
( (true == this.HasSal)
&& (typeof(Class2) == obj.GetType())
)
)
)
{
throw new ArgumentException("invalid obj");
}
Contract.EndContractBlock();
objM.Method2(obj);
.....
}
}
class Model
{
public void Method2(object obj)
{
Contract.Requires(
( (false == this.HasSal)
&& (typeof(Class1) == obj.GetType())
)
||
( (true == this.HasSal)
&& (typeof(Class2) == obj.GetType())
)
);
.....
}
}
Now whenever I try to build the code, Visual studio produces following warning
Code contracts: Requires unproven
(
( (false == this.HasSal)
&& (typeof(Class1) == obj.GetType())
)
||
( (true == this.HasSal)
&& (typeof(Class2) == obj.GetType())
)
)
Please suggest.
As rtrokzzz have given link to another SO question .NET 4 Code Contracts: “requires unproven: source != null” in comments
Solution for you is to add Contract.Ensures
in Method1()
and Method2()
Please note: I have not used Code Contracts
but I believe from my understanding that code will be as
Contract.Ensures(obj != null);
Contract.Requires(obj != null);
Refer: How to avoid “source !=null” when using Code Contracts and Linq To Sql?
I don't believe that the static checker will ever be able to verify your contract, because the type of obj
isn't known until run-time - there is no guarantee that only objects of type Class1
or Class2
will be passed to Method1
.
It might be possible to prove this by adding additional contracts to methods that call Method1
. If you include that code, I might be able to suggest a way to satisfy the static checker.
EDIT: Actually, there's another problem too. If HasSal
is a public-setter property, then I'm not sure your contract can be verified - there's always a possibility that another thread could change the value of HasSal
in between Method1
being called and the method body being executed.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.