2011-04-04 25 views
1

遇到問題我在一個類中下列屬性...與.NET泛型

public IObjectSet<Foo> Foos { get; set; } 
public IObjectSet<Baa> Baas { get; set; } 
public IObjectSet<PewPew> Pew^2 { get; set; } 

我想返回的屬性之一的值,基於如何預先確定的泛型類型。

例如。

public IObjectSet<T> Set<T>() where T : class 
{ 
    // THIS CODE DOESN'T COMPILE. 
    if (T is User) 
    { 
     return Users as IObjectSet<T>; 

    } 
    else if (T is Clan) 
    { 
     return Clans as IObjectSet<T>; 
    } 
} 

所以當我有一個特定類型的..我需要找回正確的數據類型。

例如。

return TheClass.Set<Foo>().AsQueryable(); 

這可能嗎?

回答

6
if (typeof(T) == typeof(User)) 
1

使用此:

if(typeof(T) == typeof(User)) 
2

Is是用來當你有一個實例,你需要使用

if (typeof(T) == typeof(User)) ..