泛型和类型推断
本文关键字:类型 泛型 | 更新日期: 2023-09-27 17:47:22
我有一个抽象的泛型类BLL<T> where T : BusinessObject
。我需要打开一个包含一组具体 BLL 类的程序集,并在字典中返回元组(businessObjectType,concreteBLLType)。到目前为止,我可以做这种方法的一部分,但我在发现 T 时遇到了问题。
protected override Dictionary<Type, Type> DefineBLLs()
{
string bllsAssembly = ConfigurationManager.AppSettings["BLLsAssembly"];
Type[] types = LoadAssembly(bllsAssembly);
Dictionary<Type, Type> bllsTypes = new Dictionary<Type, Type>();
foreach (Type type in types)
{
if (type.IsSubclassOf(typeof(BLL<>)))
/* how to know T in the situation below? */
bllsTypes.Add(??businessObjectType (T)??, type);
}
return bllsTypes;
}
所以具体的类会被关闭而不是泛型?这是一个简短的程序,展示了我认为你所追求的......
using System;
using System.Reflection;
public abstract class Base<T>
{
}
public class Concrete : Base<string>
{
}
class Test
{
static void Main()
{
Type type = typeof(Concrete);
Type baseType = type.BaseType;
Type typeOfT = baseType.GetGenericArguments()[0]; // Only one arg
Console.WriteLine(typeOfT.Name); // Prints String
}
}
请注意,这里我假设我们只需要上一级即可获得适当的基类型,并且具体类将被关闭。当然,您希望在实际代码中进行更多检查,但我怀疑您缺少对GetGenericArguments的调用。
乔恩,这正是我想要的。我使用反射和泛型的基础知识,所以当需要更深入的 API 知识来面对两者时,我想念这样的事情,谢谢你的回答。
你的假设是正确的,具体类是封闭的,T是在基类(BLL)上定义的。
代码变成了这样:
protected override Dictionary<Type, Type> DefineBLLs()
{
string bllsAssembly = ConfigurationManager.AppSettings["BLLsAssembly"];
Type[] types = LoadAssembly(bllsAssembly);
Dictionary<Type, Type> bllsTypes = new Dictionary<Type, Type>();
foreach (Type bllType in types)
{
if (bllType.IsSubclassOf(typeof(BLL<>)))
{
Type baseType = bllType.BaseType;
Type businessObjectType = baseType.GetGenericArguments()[0];
bllsTypes.Add(businessObjectType, bllType);
}
}
return bllsTypes;
}