[英]Create Generic Method in C#
我有以下结构:
public enum MyTypes
{
Type1 = 1,
Type2 = 2,
Type3 = 3
}
public abstract class class1
{
int id;
string name;
MyType type;
}
public class class2 : class1
{
}
public class class3 : class1
{
}
public class class4 : class1
{
}
现在我想要做的是创建一个泛型方法,我想给它一个对象类型,比如类 3,它将从类 3 创建对象并定义它的变量并返回它以便能够将它添加到列表中1级
像那样
private class1 myFunction (MyType t , int id , string name)
{
T obj = new T();
obj.type = t ;
obj.id = id ;
obj.name = name;
return obj;
}
如何创建这个通用方法?
请尽快帮助我
提前致谢
正如 Danny Chen 在他的回答中所说,您必须稍微修改您的类定义才能使其工作,然后您可以执行以下操作:
public T myFunction<T>(int id, string name) where T : class1, new()
{
T obj = new T();
obj.id = id;
obj.name = name;
return obj;
}
这个泛型方法需要从class1
派生出类型参数T
并且还有一个无参数构造函数——这就是where T : class1, new()
意思。
由于id
和name
属性是通过class1
基类定义的,因此您可以将它们设置为通过其参数传递给myFunction
任何内容。
关于class1
更多注意事项:
class1
成为接口而不是抽象类,因为它不包含任何功能。id
, name
, type
需要是 public 如果你真的想能够访问它们。public
。 考虑为此目的使用属性。不,这是不可能的,因为所有这些类都是abstract
(无法实例化)。 我们无法创建抽象类的实例。
如果我理解正确,您会问如何创建工厂模式。 这正是这个模式的设计目的:指定你想要的对象类型,然后它返回给你。
或者,您可以在函数中的类型上使用开关。
private class1 myFunction (MyType t , int id , string name)
{
class1 obj;
switch(t)
{
case MyTypes.Type1:
obj = new Class1();
...
}
obj.type = t ;
obj.id = id ;
obj.name = name;
return obj;
}
第三种方法是使用泛型。
private T myFunction<T>(MyType t , int id , string name) where T : class1, new()
{
T obj = new T();
obj.type = t ;
obj.id = id ;
obj.name = name;
return obj;
}
你会这样称呼它:
var obj = myFunction<Class3>(MyTypes.Type3, 5, "some name");
您正在寻找的基本上是抽象工厂设计模式。 http://en.wikipedia.org/wiki/Abstract_factory_pattern
做类似下面的事情
private class1 createSpecializedType<T>(MyType t, int id, string name) where T: class1, new()
{
T obj = new T();
obj.type = t ;
obj.id = id ;
obj.name = name;
return obj;
}
public class1 createMyType(MyType t, int id, string name)
{
switch(t)
{
case Type1:
return this.createSpecializedType<class2>(t, id, name);
case Type2:
return this.createSpecializedType<class3>(t, id, name);
case Type3:
return this.createSpecializedType<class4>(t, id, name);
}
}
代码未经测试,应视为伪代码。
这将允许您调用 createMyType ,它将通过参数找出您想要的类并返回正确的对象。
PS:当然这些类是抽象的,不能被实例化。 但我怀疑这是复制/重写代码时引入的错误。
如果我理解正确的话, MyTypes
和类的实际类型表示相同的事情。 在这种情况下,您需要从MyTypes
到实际类进行某种映射,例如:
static Dictionary<MyTypes, Type> typeMapping = new Dictionary<MyTypes, Type>
{
{ MyTypes.Type1, typeof(class2) },
{ MyTypes.Type2, typeof(class3) },
{ MyTypes.Type2, typeof(class4) },
};
然后,您可以使用反射来创建指定类型的实例:
private class1 myFunction(MyType t, int id, string name)
{
class1 obj = (class1)typeMapping[t].GetConstructor(Type.EmptyTypes).Invoke(null);
obj.type = t ;
obj.id = id ;
obj.name = name;
return obj;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.