Describes the constraints of C generic classes in use

  • 2020-05-19 05:31:32
  • OfStack

First, take a look at the basic syntax for generics

The access modifier returns the type generic method name < T > (T parameters)

1) : you cannot create an instance of an object of any T type inside a generic method, because you do not know what constructors the passed object has inside a generic method
2) : the constraint is on the inside! Constraints are also inherited (for generic methods)!

3) : constraint on adding type (reference type, value type) to generic class: where T:class,new ()

Problems encountered:
When writing the MongodbHelper class, in order to handle multiple categories, the class is defined as follows:


 public class MongodbHelper<T>
 {
 . 
  }

In the implementation of this class, there are the following operations:

mongo.Connect();
var db = mongo.GetDatabase(_databaseName);
var collection = db.GetCollection<T>(_collectionName);
collection.Insert(t, true);
mongo.Disconnect();


This is the way to insert mongo, at this point, db.GetCollection < T > (_collectionName) the T here causes the compilation to fail, so the above definition is found to be incorrect. GetCollection's signature is as follows:

IMongoCollection < T > GetCollection < T > (string name) where T : class;

It has its own special constraints on T, therefore

The corresponding constraint should be added to the definition to ensure that constraint 1 of T is correct.


Related articles: