繁体   English   中英

我怎样才能让这个方法从使用中推断类型参数?

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

我想使用TryGet方法来推断类型参数,就像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);
    }
}

以下是MaterialGetIntSetInt的签名:

int GetInt(int);

int GetInt(string);

void SetInt(int, int);

void SetInt(string, int);

这是可能的,还是我对编译器的要求太多了?

因为TryGet固有地返回一个值,所以选择要返回的值是有意义的:

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

问题解决了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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