Several common methods with the same names and arguments, but different results and limitations

I am currently rewriting parts of a custom RPC engine (which cannot be replaced with anything else, so don't suggest this ;-)). Call arguments are collected in a user collection that uses an internal dictionary. There is a method T Get<T>(string)for getting a named argument. For optional arguments, I wanted to add a method TryGet<T>(string)that returns an argument or null, if it does not exist, so that the calling code can provide a default value using the zero coalescence operator. Of course, for the value type, this does not work, but instead I could use T?what I want.

So, I have this:

public class Arguments
{
    // lots of other code here

    public T TryGet<T>(string argumentName) where T : class
    {
        // look up and return value or null if not found
    }

    public T? TryGet<T>(string argumentName) where T : struct
    {
        // look up and return value or null if not found
    }
}

:

return new SomeObject(
                      args.TryGet<string>("Name") ?? "NoName",
                      args.TryGet<int>("Index") ?? 1
                      );

, ( , ). , TryGet .

- , ?

+3
4

, , , ( ). , , :

public T TryGet<T>(string argumentName)
{
    if (!_internalDictionary.ContainsKey(argumentName))
    {
        return default(T);
    }
    return (T)_internalDictionary[argumentName];
}
+3

, .NET Framework , TryGetValue out. get, out ( ) ( ).

. .

. Dictionary<TKey,TValue>.TryGetValue.

+5

Limitations are not part of the signature. so the answer to your question is no.

+5
source

An alternative solution might be the following:

public class Arguments {
    public T Get<T>(string argumentName,T defaultValue) {
        // look up and return value or defaultValue if not found
    }
}

return new SomeObject(
    args.Get<string>("Name","NoName"),
    args.Get<int>("Index",1)
);

In this particular case, you will not even need to specify a generic type, as it can be inferred by default:

return new SomeObject(
    args.Get("Name","NoName"),
    args.Get("Index",1)
);
+3
source

Source: https://habr.com/ru/post/1732976/


All Articles