我有一个关于C#泛型和委托的问题:
首先我描述一般问题—我想要一个委托集合,这些委托应该有一个类似的形式,例如,我的所有委托都应该有这样的形式:取两个相同类型的参数,然后返回int.我想建模这些委托的最好方法是使用泛型委托:
public delegate int MyFunctionDel <T> (T a,T b);
但是如何创建具有不同类型的MyFunctionDel集合?我无法宣布:
List<MyFunctionDel <T>> mylist; //Compile error: cannot find type T
其次,这就是我实际上要做的事情.我想做的事可以通过上述问题解决.但是你可以提供其他解决方案.
我写了一个类似集合的结构:它可以保存任何类型的数据.但是结构中的所有数据都应该是相同的类型.不幸的是,由于某些历史原因,这种结构并不通用.该结构具有Compare方法.
但现在我需要为某些特定类型提供定制的比较器.我想要的行为是:如果有一个数据类型,struture使用自定义比较器,否则使用原始的Compare方法.这是我的演示代码:
/* *This piece of code demonstates my idea,but never works */ static class Program { [STAThread] static void Main() { MyStructure s = new MyStructure (); //create a customized comparer using Comparison<T> generic delegate Comparison <string> myStirngComparer = (x,y)=> { return -x.Compareto(y); }; s.CustomizedComparers[typeof(string)] = myStirngComparer; System.Console.WriteLine (s.Compare("a","b")); //I am expecting the result to be 1 } } class MyStructure { //For simplicity,I won't put storage related code here public int Compare (object o1,object o2) { //let's suppose o1 and o2 are always of same type switch (o1.GetType()) { case TypeCode.Single: return Compare<Single> ((Single)o1,(Single)o2); case TypeCode.Double: return Compare<Double> ((Double)o1,(Double)o2); case TypeCode.String: return Compare<String> ((String)o1,(String)o2); //and so on..... } return 0; } //NOTE: code below won't work //But my logic is: use a Dictionary to store a map from "Type" to "Comparison<T>" //When doing the comparison,we first examine if there exists one Comparison<T> for //Type T in the Dictionary //Compile Failed here public Dictionary <Type,Comparison<T> > CustomizedComparers = new Dictionary <Type,Comparison<T> > (); private int Compare<T> (T a,T b) { if (CustomizedComparers.ContainsKey(typeof(T))) { Comparison<T> comp = CustomizedComparers[typeof(T)]; return comp (a,b); } else return Comparer<T>.Default.Compare(a,b); } }
欢迎任何评论,建议和见解!感谢你们.
解决方法
您可以创建Dictionary< Type,Delegate>并在请求时将委托转换为正确的类型.考虑使用helper类而不是普通的Dictionary< Type,Delegate>:
public class ComparersCollection { private readonly Dictionary<Type,Delegate> _comparers = new Dictionary<Type,Delegate>(); public void OverrideComparison<T>(Comparison<T> comparison) { if(comparison == null) { _comparers.Remove(typeof(T)); } else { _comparers[typeof(T)] = comparison; } } public Comparison<T> GetComparison<T>() { Delegate comparison; if(_comparers.TryGetValue(typeof(T),out comparison)) { return (Comparison<T>)comparison; } else { return Comparer<T>.Default.Compare; } } }
现在你可以使用:
Comparison <string> myStringComparer = (x,y) => -x.Compareto(y); s.CustomizedComparers.OverrideComparison(myStringComparer);
和
var comparison = CustomizedComparers.GetComparison<T>(); return comparison(a,b);