在C#中创建通用方法 [英] Create Generic Method in C#

查看:49
本文介绍了在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的列表

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#中创建通用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆