我具有以下结构:
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的列表
now what I want to do is to make a generic method , I want to give it the type of object say class 3 and it will create object from class 3 and define it's variables and return it to be able to add it to a list of class1
喜欢
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在回答中所说的那样,您必须对类定义进行一些修改才能使其起作用,然后您可以执行以下操作:
As Danny Chen says in his answer, you will have to modify your class definitions a little for it to work, then you could do something like the following:
public T myFunction<T>(int id, string name) where T : class1, new() { T obj = new T(); obj.id = id; obj.name = name; return obj; }此通用方法要求类型参数 T 从 class1 派生,并且还具有无参数的构造函数-这就是 where T:class1,new()表示.
This generic method requires type parameter T to be derived from class1 and also to have a parameter-less constructor -- that's what the where T : class1, new() means.
由于 id 和 name 属性是通过 class1 基类定义的,因此您可以将它们设置为传递给的内容myFunction 通过其参数.
Since id and name properties are defined through the class1 base class, you can then set these to whatever was passed into myFunction via its parameters.
关于 class1 的更多注意事项:
- 考虑将 class1 用作接口而不是抽象类,因为它不包含任何功能. 如果您确实希望访问它们,则
- id ,名称, type 必须公开.
- 通常,字段实际上并不公开为 public .考虑为此使用属性.
- Consider making class1 an interface instead of an abstract class, as it doesn't contain any functionality.
- id, name, type need to be public if you actually want to be able to access them.
- Usually, fields aren't actually exposed as public. Consider using properties instead for that purpose.
更多推荐
在C#中创建通用方法
发布评论