I am just getting started with Code Contracts, and need a little he开发者_Go百科lp in correcting an error:
Given this code:
class MyClass
{
private bool _isUsed = false;
public void SomeMethod()
{
Contract.Requires(!_isUsed);
}
}
I get the following error:
error CC1038: Member 'MyClass._isUsed' has less visibility than the enclosing method 'MyClass.SomeMethod'
which seems to makes alot of the standard checks unavailable. What am I missing in this example?
It has already been explained that either _isUsed
has visibility issues (caller does not have control) which is rightly enforced by requires.
However, depending on what you are trying to accomplish with the Contract, Contract.Assert
may meet your needs.
public void SomeMethod()
{
Contract.Assert(!_isUsed);
}
would be valid while the Requires was not.
You have a public method SomeMethod. However, you're requiring that a private member variable is set to false. You provide no way of setting _isUsed, and so you're putting a check on a variable that a caller has no control over.
You could make _isUsed into a property i.e.
public bool IsUsed {get; set;}
And then in your SomeMethod() have
Contract.Requires(!IsUsed);
精彩评论