2008-10-24 141 views
1

我有一個抽象泛型類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; 
} 
+0

那麼,是什麼牛逼涉及到了這裏?目前尚不清楚(對我而言)代碼是什麼。 – 2008-10-24 12:03:27

+0

我想Jon可能會爲你清除代碼。 – 2008-10-24 12:25:21

回答

3

所以具體的類將被關閉,而不是泛型?這裏有一個簡短的程序這說明什麼,我覺得你之後...

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

0

喬恩,那正是我在找的東西。我使用反射和泛型的基礎知識,所以當需要更深入的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; 
}