2015-12-26 47 views
1

我想組裝一個泛型方法,它傳遞類類型的對象(即:dbJob)還有像'LastUpdatedDate'這樣的子類的名字和一個過程字符串,可以是'> 01-01-2015'。如何訪問object.GetType()的子類屬性時,只有子類的名稱作爲字符串

的方法是這樣的

public bool checkProcess(object obj, string className, string processStr) 
{ 
    PropertyInfo[] propertyInfo; 
    bool returnValue = false; 
    propertyInfo = obj.GetType().GetProperties(); 
    //propertyInfo className evaluate processStr 
    return returnValue; 
} 

我使用反射來獲取我的類的屬性信息。說我傳遞dbJob,我怎麼能使用字符串說'LastUpdatedDate'的子類來讓我的屬性來評估processStr?

回答

0

只要試着將它轉換成as這個類型,如果它能成功地被轉換,那麼就可以從該類型中獲取屬性。

var subClass = obj as SubClass; 
if (subClass != null) 
{ 
    var type = subClass.GetType(); 
    var props = type.GetProperties(); 
    ... 
} 

作爲一個評論,如果你有控制類,你最好使用接口這種事情。

定義接口:

public interface IYourInterface 
{ 
    string SomeMethod(); 
} 

實現你的類接口(如需要的類可以實現多個接口)

public class YourSub : IYourInterface 
{ 
    ... other methods/props ... 

    public string SomeMethod() 
    { 
     return "blah"; 
    } 
} 

現在你可以只投的對象爲接口,如果它起作用,則調用該方法。

var subClass = obj as IYourInterface; 
if (subClass != null) 
{ 
    var str = subClass.SomeMethod(); //done 
} 
+0

這是一個很棒的提示,謝謝,我會試試看 – user616076