Created
April 17, 2013 05:30
-
-
Save Eibwen/5402004 to your computer and use it in GitHub Desktop.
Fun with interfaces
Any object or list of objects to formatted string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void Main() | |
{ | |
_filters.Add("Integer", new FilterItem<int>(999)); | |
_filters.Add("IntegerList", new FilterListItem<int>(new [] { 1, 2, 3, 863, 2452, 24 })); | |
_filters.Add("string", new FilterItem<string>("test str")); | |
foreach (var kvp in _filters) | |
{ | |
kvp.Value.GetQueryString().Dump(); | |
} | |
} | |
Dictionary<string, IFilterItem> _filters = new Dictionary<string, IFilterItem>(); | |
public interface IFilterItem | |
{ | |
object StorageObject(); | |
string GetQueryString(); | |
Func<IFilterItem, string> StringConverter { get; } | |
} | |
public class FilterItem<T> : IFilterItem | |
{ | |
public FilterItem() | |
{ } | |
public FilterItem(T value) | |
{ | |
_value = value; | |
} | |
public FilterItem(Func<IFilterItem, string> stringConverter) | |
{ | |
if (stringConverter != null) | |
StringConverter = stringConverter; | |
} | |
T _value; | |
public virtual void SetOrAdd(T value) | |
{ | |
_value = value; | |
} | |
public virtual object StorageObject() | |
{ | |
return _value; | |
} | |
public virtual string GetQueryString() | |
{ | |
return StringConverter(this); | |
} | |
Func<IFilterItem, string> _StringConverter = (x => x.StorageObject().ToString()); | |
public virtual Func<IFilterItem, string> StringConverter | |
{ | |
get { return _StringConverter; } | |
private set { _StringConverter = value; } | |
} | |
} | |
public class FilterListItem<T> : FilterItem<T>, IFilterItem | |
{ | |
public FilterListItem() | |
: base(x => string.Join(",", ((List<T>)x.StorageObject()).Select(i => i.ToString()).ToArray())) | |
{ } | |
public FilterListItem(IEnumerable<T> values) | |
: this() | |
{ | |
AddRange(values); | |
} | |
List<T> _value = new List<T>(); | |
public override void SetOrAdd(T value) | |
{ | |
_value.Add(value); | |
} | |
public void AddRange(IEnumerable<T> value) | |
{ | |
_value.AddRange(value); | |
} | |
public override object StorageObject() | |
{ | |
return _value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment