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

╄→尐↘猪︶ㄣ 提交于 2019-12-07 19:41:30

问题


Suppose we have a generic method with such signature:

T Obfuscate<T>(T value) where T : IConvertible

I'm setting type constraint to IConvertible so this method can digest simple value types as well as strings. Let's forget for a moment that enums can also be supplied...

I would like to avoid such implementation that would check actual parameter type to execute correct processing.

// Please no GOD METHODS
public T Obfuscate<T>(T value)
    where T : IConvertible
{
    if (value is int)
    {
        ...
    }
    if (value is string)
    {
        ...
    }
}

This surely smells of a factory method, that would have to call particular implementation provider, but that would still require type checking.

What would you suggest be best (hopefully generic approach) to this scenario?

Why a generic method?

I decided to have a generic method so it always returns correct type without the need to cast method returns in calling code.


回答1:


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?
}


来源:https://stackoverflow.com/questions/23957027/best-way-to-implement-a-generic-method-in-a-type-generic-agnostic-way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!