Home >Backend Development >C++ >Can Generic Types with Parameterized Constructors Be Instantiated in C#?
This article explores how to instantiate a generic type with a parameterized constructor in C#.
Suppose there is a generic method for adding fruits to the fruit manager:
<code class="language-csharp">public void AddFruit<T>() where T : BaseFruit { BaseFruit fruit = new T(weight); // 例如:new Apple(150) fruit.Enlist(fruitManager); }</code>
where BaseFruit
class has a constructor that takes an integer weight
as parameter.
Question: Can we instantiate a fruit object with a specific weight in this generic method?
Answer: Yes, but not directly like in the example. There are two methods:
1. Use Activator class:
Using the Activator
class, we can dynamically instantiate an object of type T
and pass the required parameters as an array of objects:
<code class="language-csharp">return (T)Activator.CreateInstance(typeof(T), new object[] { weight });</code>
Note that this requires the BaseFruit
class to have a public parameterless constructor for the compiler to check, but in reality it uses the Activator
class to create the instance.
2. Use generic parameters with constructor:
C# restricts the use of constructors that require parameters to instantiate generic types. As a workaround, you can create a generic parameter with the same name as the type and specify the constructor parameter in its definition:
<code class="language-csharp">public void AddFruit<T>(T fruit) where T : new(int weight) { fruit.Enlist(fruitManager); } // 使用示例: AddFruit(new Apple(150));</code>
However, this approach is generally not recommended as it can lead to code smells related to constructor requirements in generic types.
The above is the detailed content of Can Generic Types with Parameterized Constructors Be Instantiated in C#?. For more information, please follow other related articles on the PHP Chinese website!