Best way to implement a generic method in a type generic/agnostic way

拜拜、爱过 提交于 2019-12-06 09:28:44
Jon Skeet

As you say, you've got to perform type checking of some description. However, you can easily break it down into smaller methods and even have an open registration scheme:

private readonly Dictionary<Type, Delegate> obfuscators =
    new Dictionary<Type, Delegate>;

// Alternatively, register appropriate obfuscators on construction.
public void RegisterConverter<T>(Func<T, T> obfuscator)
{
    obfuscators[typeof(T)] = obfuscator;
}

public T Obfuscate<T>(T value)
{
    Delegate obfuscator;
    if (obfuscators.TryGetValue(typeof(T), out obfuscator)
    {
        // We know it'll be the right type...
        var realObfuscator = (Func<T, T>) obfuscator;
        return realObfuscator(value);
    }
    // ??? Throw exception? Return the original value?
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!