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.
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