简体   繁体   中英

How to create contract class for class with required constructor arguments?

I have an abstract class whose constructor requires a parameter. The parameter cannot be null.

// the abstract class
[ContractClass(typeof(AbstractClassContract))]
public abstract class AbstractClass
{
   // Constructor with required parameter
   protected AbstractClass(SqlConnection connection)
   {
      Contract.Requires(connection != null);
      Connection = connection;
   }

   protected SqlConnection Connection { get; set; }

   public abstract string GetSomething();
}

The abstract class has a contract class for checking pre/post-conditions on abstract members.

// the contract class
[ContractClassFor(typeof(AbstractClass))]
public abstract class AbstractClassContract
{
   public override string GetSomething()
   {
      Contract.Ensures(Contract.Result<string>() != null);
      return default(string);
   }
}

The above code doesn't compile because of the error 'AbstractClass' does not contain a constructor that takes 0 arguments .

I can add a constructor, like below, and the code will compile and seems to work.

   public AbstractClassContract(SqlConnection connection)
      : base(connection)
   { }

But is this a valid constructor for a contract class? Will it cause a problem in some situation? My concern is that the parameter is ultimately required by the abstract class's constructor.

If it is valid, then how is .NET getting around the required parameter limitation?

It's been a while since I looked at Code Contracts, but I'd expect that your contract class was never actually instantiated. Instead, the contracts checker will basically suck the code from your contract class into each concrete subclass.

So if I'm write, your constructor in AbstractClassContract should be fine. Or you could just use new SqlConnection("this is never called") to be clearer :)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM