如何将 class 类型分配给泛型类型 <T>?

How to assign class type to generic Type <T>?

我有一个 class 来执行如下特定逻辑:

public abstract class BaseSchema<T> : iMyInterface
    {
        public List<T> GetSchemaObjects<T>(string csvData) where T : iMyInterface
        {
            var records = new List<T>();
            using (var streamReader = new StreamReader(csvData))
            {
                using (var csvReader = new CsvReader(streamReader, CultureInfo.InvariantCulture))
                {
                    records = csvReader.GetRecords<T>().ToList();
                }
            }
            return records;
        }
    }

现在我想用 Class 作为参数调用此方法。我有 class 的类型对象。通话时如何分配?

public List<T> GetTestSchema<T>(string versionNumber, string schemaName) where T : iMyInterface
        {
Type[] allSchemaTypes = Assembly.GetExecutingAssembly().GetTypes()
                                .Where(t => t.IsClass && t.Namespace.StartsWith($"{schemaNamespace}") 
                                        && !t.GetCustomAttributes(typeof(ObsoleteAttribute), true).Any())
                                .ToArray();            
int indexNumber = GetIndexNumberOfRequiredVersion(versionNumber);
            Type schemaType = allSchemaTypes
                                .Skip(indexNumber)
                                .Where(x => x.Name.Equals(schemaName) && interfaceType.IsAssignableFrom(x))
                                .FirstOrDefault();
            var objj = (iMyInterface)schemaType.Assembly.CreateInstance(schemaType.ToString());
            //Type objjType = Type.GetType(objj);
            return objj.GetSchemaObjects<schemaType>(@"CSV Path"); // This line gives an error as Cannot implicitly convert type List<schemaType> to List<T> but generic should accept it. Isn't it?
        }

您可以使用 MakeGenericMethod 类似的东西:

MethodInfo getSchemaObjectsMethod = typeof(iMyInterface).GetMethod("GetSchemaObjects");
MethodInfo getSchemaObjectsGeneric = getSchemaObjectsMethod.MakeGenericMethod(schemaType);
return getSchemaObjectsGeneric.Invoke(null, new object[] { "CSV Path" });

参见:How do I use reflection to call a generic method?