泛型参数

本文关键字:参数 泛型 | 更新日期: 2023-09-27 18:35:13

我有四个具有相似结构的EF类和一个包含EF结构和其他一些 props 和方法的泛型类,并且想要编写一个泛型方法转换为所需的EF

private List<T> CastGenericToEF<T>(List<GenericClass> GenericList)
{
    List<T> Target = new List<T>();
    foreach (GenericClass I in GenericList)
    {
        //How can I do to create an Instance of T?
        ..... 
        // Some proccess here 
    }
    return Target;
}

我的问题:如何创建 T 类型的新实例或获取 T 的类型

泛型参数

您需要在 T 上添加约束:

private List<T> CastGenericToEF<T>(List<GenericClass> GenericList) where T : new()

然后,您可以使用 T 创建 T 的实例new T()

要获取 T 的类型,只需使用 typeof(T)

你必须

定义 T 可以有 new()

private List<T> CastGenericToEF<T>(List<GenericClass> GenericList) where T: new()
{
    List<T> Target = new List<T>();
    foreach (var generic in GenericList)
    {
        //How can I do to create an Instance of T?
        var tInstance = new T();
        // Some proccess here 
        var typeOf = typeof(T);
    }
    return Target;
}

要访问 T 的属性/方法,您必须以某种方式指定其类型。没有规范,T 可以是任何东西......

下面的示例在某处定义一个接口,然后指定 T 必须实际实现该接口。如果你这样做

    interface IGenericClass
    {
        void SomeMethod();
    }

您可以访问接口定义的属性或方法

    private List<T> CastGenericToEF<T>(List<GenericClass> GenericList) where T : IGenericClass, new()
    {
        List<T> Target = new List<T>();
        foreach (var generic in GenericList)
        {
            //How can I do to create an Instance of T?
            var tInstance = new T();
            tInstance.SomeMethod();
            // Some proccess here 
            var typeOf = typeof(T);
        }
        return Target;
    }