Mixing Generics in Collections
I’ve been heavily working with generics over the past few weeks for the final re-factor of LiveFlex. Generics are fantastic but they do have some annoying limitations. You can’t, for instance, create a List<T> and add mixed types such as Item<String>, Item<int> as they are created as seperate classes.
To get around this issue you have to create a common interface or class which kinda misses the point. I’m using generics so we don’t have to cast the objects passed to the rules.
This is how I managed to mix the generic types in the property validation rules.
/// <summary> /// Wrapper class so we can store different generic instances in a collection /// </summary> public abstract class PropertyRule { public abstract bool Check(); }
public class PropertyRule<T, U> : PropertyRule { public override bool Check() { U val = GetValue(PropertyName); return CheckMethod.Invoke(val); } }
List<PropertyRule> RuleList = new List<PropertyRule>(); PropertyRule<ExampleObject, String> ValidEmail= new PropertyRule<ExampleObject, string>(o, "PropTwo", IsEmail); PropertyRule<ExampleObject, String> stringnotempty = new PropertyRule<ExampleObject, string>(o, "PropTwo", delegate(String val) { return val.IsNotEmpty(); }); foreach(PropertyRule n in RuleList) { Response.Write(Reflection.GetName(() => n) + "=" + n.Check() + "<br/>"); }
Leave a Reply