SoFunction
Updated on 2025-03-06

Introducing the constraints of C# generic classes in use

First, let’s take a look at the basic syntax of generics

Access modifier Return type Generic method name <T>(T parameter)

1): The object that cannot be created for any T type inside the generic method, because the constructors of the object passed in are not known inside the generic method.
2): Constraints are internal! (For generic methods) constraints will also be inherited!

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

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

Copy the codeThe code is as follows:

 public class MongodbHelper<T>
 {
。。。。。
}

In the implementation of this class, there are the following operations:
Copy the codeThe code is as follows:

();

var db = (_databaseName);

var collection = <T>(_collectionName);

(t, true);

();



This is a method to insert mongo. At this time, the T here in <T>(_collectionName) causes the compilation to be unable to pass, so the above definition is found to be incorrect. The signature of GetCollection is as follows:

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

It has special constraints on T, so

When defining, corresponding constraints should be added to ensure that the constraints of T are consistent.