Last active
August 29, 2015 14:04
-
-
Save yicone/7ad1b5ac23a0bbe611e9 to your computer and use it in GitHub Desktop.
泛型特化时,一般会遭遇无法用集合法来消除针对类型参数的 if 语句。通过使用匿名委托(需要静态泛型类作为 Holder),可以避免。其效果可以形容为作用于类型参数的模式匹配。如此也避免了可能存在的类型转换所带来的装箱/拆箱操作。
This file contains hidden or 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() | |
{ | |
IRecord record = new Record1(); | |
Console.WriteLine (record.Get<int>("aaa")); | |
} | |
public interface IRecord { | |
string GetString(string field); | |
int GetInt(string field); | |
long GetLong(string field); | |
} | |
public class Record1 : IRecord{ | |
public string GetString(string field){return "1";} | |
public int GetInt(string field) {return 1;} | |
public long GetLong(string field) {return 1l;} | |
} | |
//public static class RecordExtensions { | |
// public static T Get<T>(this IRecord record, string field) { | |
// if(typeof(T) == typeof(string)) | |
// return (T)(object)record.GetString(field); | |
// if(typeof(T) == typeof(int)) | |
// return (T)(object)record.GetString(field); | |
// if(typeof(T) == typeof(long)) | |
// return (T)(object)record.GetString(field); | |
// return default(T); | |
// } | |
//} | |
public static class RecordExtensions2 { | |
private static class Cache<T>{ | |
public static Func<IRecord, string, T> Call; | |
} | |
static RecordExtensions2(){ | |
Cache<string>.Call = (record, field) => record.GetString(field); | |
Cache<int>.Call = (record, field) => record.GetInt(field); | |
Cache<long>.Call = (record, field) => record.GetLong(field); | |
} | |
public static T Get<T>(this IRecord record, string field) { | |
if(Cache<T>.Call != null) | |
return Cache<T>.Call(record, field); | |
return default(T); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment