Where T:Class,new()的使用
时间: 2023-07-11 20:14:03 浏览: 103
"Where T : class, new()" is a constraint in C# generics that ensures that the type parameter T is a reference type (i.e., a class) and has a public parameterless constructor. This allows you to create instances of T using the "new" keyword within the generic class or method.
For example, consider the following code:
```
public class Example<T> where T : class, new()
{
public void DoSomething()
{
T instance = new T();
// Do something with the instance
}
}
```
Here, the "Example" class is a generic class that takes a type parameter T. The "where T : class, new()" constraint ensures that T is a reference type and has a public parameterless constructor. Within the "DoSomething" method, we can create an instance of T using the "new" keyword, knowing that the type parameter satisfies the constraint.
This constraint is useful when you need to create instances of a generic type within the generic class or method, but you don't know the exact type of T at compile time.
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)