【问题标题】:Generics and Type inference泛型和类型推断
【发布时间】:2008-10-24 11:59:38
【问题描述】:

我有一个抽象泛型类BLL<T> where T : BusinessObject。我需要打开一个包含一组具体 BLL 类的程序集,并在 Dictionary 中返回元组(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;
}

【问题讨论】:

  • 那么,这里的 T 与什么有关?目前尚不清楚(至少对我而言)代码代表什么。
  • 我认为 Jon 可能为你清除了代码。

标签: c# generics reflection


【解决方案1】:

所以具体的类将是封闭的而不是通用的?这是一个简短的程序,展示了我认为你所追求的......

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 的调用。

【讨论】:

    【解决方案2】:

    乔恩,这正是我想要的。我使用反射和泛型的基础知识,所以当需要更深入的 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;
    }
    

    【讨论】:

    • 我至少要添加一条评论说:“如果我们有更深的类层次结构,这将打破!”只是让你知道当它爆炸时出了什么问题:)
    • 好吧,乔恩,在我的情况下,BLL 同时是具体基类的直接基类,而 BLL 本身不使用继承;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-17
    相关资源
    最近更新 更多