简体   繁体   中英

How can I get this method to infer type argument from usage?

I would like to get TryGet method to infer the type argument, just as it is possible for TrySet :

private void Test()
{
    TryGet<int>(RefProperty, s => s.GetInt); // works fine

    TryGet(RefProperty, s => s.GetInt); // CS0411 here

    TrySet(RefProperty, s => s.SetInt, 1234);
}

private T TryGet<T>(int property, Expression<Func<Material, Func<int, T>>> expression)
{
    return Material.HasProperty(property) ? expression.Compile()(Material)(property) : default;
}

private void TrySet<T>(int property, Expression<Func<Material, Action<int, T>>> expression, T value)
{
    if (Material.HasProperty(property))
    {
        expression.Compile()(Material)(property, value);
    }
}

Here are the signatures of GetInt and SetInt in Material :

int GetInt(int);

int GetInt(string);

void SetInt(int, int);

void SetInt(string, int);

Is this possible somehow or am I asking the compiler too much?

Because TryGet inherently returns a value, it makes sense to choose the value to return:

private void Test()
{
    TryGet(RefProperty, s => s.GetInt, 42);
}

private T TryGet<T>(int property, Expression<Func<Material, Func<int, T>>> expression, T defaultValue)
{
    return Material.HasProperty(property) ? expression.Compile()(Material)(property) : defaultValue;
}

Problem solved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM