2015-06-29 61 views
-1

我已經查看了所有對此問題的答案,但沒有找到一個有吸引力的答案。我正在嘗試創建一個TextFilter類來爲基於字符串的屬性生成簡單的可觀察集合過濾器。以下是我的想法:傳遞對象屬性作爲參數並訪問它

public class TextFilter : IFilter 
{ 
    Func<string> Property; 
    string Target { get; set; } 

    public TextFilter(Func<string>property, string target) 
    { 
     Property = property; 
     Target = target; 
    } 

    public bool Filter(object item) 
    { 
     return ((MyObject)item).***Property***.Contains(Target); 
    } 
} 

但是我找不到方法來傳遞我的屬性並在以後訪問它們?

+1

你能解釋一下你所見過的標準委託解決方案不適合你的情況嗎 - 比如http://stackoverflow.com/questions/1178574/how-can-i-pass-a-property-of-a -class-as-a-parameter-of-method –

+0

@Alexei Levenkov這實際上是我一直在尋找的,我剛開始並沒有意識到,謝謝! – eYe

回答

2

你可以試試這個:

public class TextFilter : IFilter 
{ 
    Func<object, string> Property; 
    string Target { get; set; } 

    public TextFilter(Func<object, string> property, string target) 
    { 
     Property = property; 
     Target = target; 
    } 

    public bool Filter(object item) 
    { 
     return Property(item).Contains(Target); 
    } 
} 

像這樣來使用:

var value = new MyObject() { Property = "This is a Test" }; 

var filter = new TextFilter(o => ((MyObject)o).Property, "Test"); 

bool isFiltered = filter.Filter(value); 

如果你不需要你TextFilters是同一類,你可以使用一個通用的TextFilter<T>,而不是使用object

如果您確實想擁有房產,您可能需要expression trees

+0

你可以給一個示例TextFilter實例嗎? – eYe

+0

對,謝謝! – eYe

相關問題