[英]Create instance of a generic type that takes a parameter a secondary generic type
I have an abstract class called Factory我有一个名为 Factory 的抽象类
The factory has a method createModel()工厂有一个方法 createModel()
public abstract class Factory<T, U>{
public T CreateModel(IDictionary<String, Object> parametersDictionary)
{
T toReturn;
if (ValidateDictionary(parametersDictionary) != true)
return null;
else
{
toReturn = new T(U);
}
return toReturn;
}}
In the else statement, I want to create a Car instance taking a CarPart object which I would get from another method call.在 else 语句中,我想创建一个 Car 实例,该实例采用我将从另一个方法调用中获取的 CarPart 对象。 This logic would be applied on other Factory subtypes so I want to inherit this method.
此逻辑将应用于其他 Factory 子类型,因此我想继承此方法。 The issue is I can't create the Car generic instance with another Generic parameter.
问题是我无法使用另一个 Generic 参数创建 Car 通用实例。
I looked around and found that I could use the Activator class.我环顾四周,发现我可以使用 Activator 类。
(T)Activator.CreateInstance(typeof( Car), args);
(T)Activator.CreateInstance(typeof(Car), args);
This however seems to work only when you have a certain type that you want to give to the constructor.然而,这似乎只有当您有某种类型要提供给构造函数时才有效。
I also tried to do:我也尝试这样做:
public abstract class Factory where T: new()
公共抽象类工厂,其中 T: new()
But that didn't let me parse any argument to the constructor.但这并没有让我解析构造函数的任何参数。
How can I implement this abstract class?如何实现这个抽象类?
Edit1: changed the naming for clarification编辑 1:更改命名以进行澄清
Edit2: For clarification, U is a structure that contains aproximatelly 20 parameters necessary for creating T. So in order to create a new T, I need to pass it a U object that encapsulates all 20 parameters necessary. Edit2:为了澄清起见,U 是一个包含创建 T 所需的大约 20 个参数的结构。因此,为了创建一个新的 T,我需要向它传递一个 U 对象,该对象封装了所有 20 个必需的参数。
After Abion47 pointed out that Activator.CreateInstance shouldn't have any issues doing what I need it to do I looked a bit more into the issue and made it work.在 Abion47 指出 Activator.CreateInstance 在做我需要它做的事情时不应该有任何问题之后,我更深入地研究了这个问题并使其工作。
For anyone that might come across this:对于可能遇到此问题的任何人:
public abstract class Sentinel<T,U> where T: new() where U: new()
{
public T CreateModel(IDictionary<String, Object> parametersDictionary)
{
T toReturn ;
if (ValidateDictionary(parametersDictionary) != true)
return default(T);
else
{
U parameters = ParseDictionaryToParameters(parametersDictionary);
toReturn = (T)Activator.CreateInstance(typeof(T), new object[] {parameters});
}
//If we got this far then everything should be fine.
return toReturn;
}
public abstract U ParseDictionaryToParameters(IDictionary<String, Object> parametersDictionary);
public abstract Boolean ValidateDictionary(IDictionary<String, Object> parametersDictionary);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.