2011-01-04 32 views
8

aşağıdaki genel sınıf Şimdispesifik türü olmayan bir genel sınıf Döküm

public class Home<T> where T : Class 
{ 
    public string GetClassType 
    { 
     get{ return T.ToString() } 
    } 
} 

, ben emin olduğum bir nesne X edilir alıyorum Ev sahiptir:

public void DoSomething(object x) 
{ 
    if(x is // Check if Home<>) 
    { 
     // I want to invoke GetClassType method of x 
     // but I don't know his generic type 
     x as Home<?> // What should I use here? 
    } 
} 

bile I Can sınıfın jenerik türünü belirtmeden döküm yapmak?

cevap

9

DoSomething argümanının Home<T> olduğuna eminseniz, neden genel bir yöntem yapmıyorsunuz? DoSomething mantıksal Home<T> bir örnek yöntemi olmalıdır eğer

public void DoSomething<T>(Home<T> home) 
{ 
    ... 
} 

Tabii ki, daha da kolay olacaktır.

public void DoSomething(object x) 
{ 
    // null checks here. 

    Type t = x.GetType(); 

    if (t.IsGenericType && 
      && t.GetGenericTypeDefinition() == typeof(Home<>)) 
    { 
     string result = (string) t.GetProperty("GetClassType") 
            .GetValue(x, null); 

     Console.WriteLine(result); 
    } 

    else 
    { 
     ... // do nothing/throw etc. 
    } 
} 
0

böyle bir şey için yöntem tanımını değiştirerek denediniz: Eğer gerçekten size ne ile sopa istiyor Eğer

, siz (denenmemiş) yansıma kullanabilirsiniz?

public void DoSomething<T>(Home<T> x) 
{ 

} 
1

İşlev genelleştirmeye ne dersin?

public void DoSomething<T>(object x) 
{ 
    if(x is Home<T>) 
    { 
     x as Home<T> ... 
    } 
} 

Düzenleme: Başka olasılıkları GetClassName böylece sadece o arayüzün olup olmadığını kontrol etmek gerekir özelliğini tutan bir arayüz oluşturmak olacaktır.

public interface IDescribeClass 
{ 
    public string GetClassName { get; set; } 
} 

BTW: Tam nitelikli adını Ev temel sınıftan türetilmiş ne

public string ClassType 
{ 
    get{ return typeof(T).FullName; } 
} 
4

kullanırdınız?

public class Home 
{ 
    public virtual string GetClassType { get; } 
} 
public class Home<T> : Home 
    where T : class 
{ 
    public override string GetClassType 
    { 
     get{ return T.ToString() } 
    } 
    ... 
} 

ve sonra

public void DoSomething(object x) 
{ 
    if(x is Home) 
    { 
     string ct = ((Home)x).GetClassType; 
     ... 
    } 
} 
İlgili konular