我怎样才能让这个方法从用法中推断类型参数?
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);
}
}
GetInt
和SetInt
在Material
中的签名:
int GetInt(int);
int GetInt(string);
void SetInt(int, int);
void SetInt(string, int);
这是可能的还是我对编译器的要求太多了?
因为 TryGet
本质上是一个 return 的值,所以选择 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;
}
问题已解决。
我想获得 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);
}
}
GetInt
和SetInt
在Material
中的签名:
int GetInt(int);
int GetInt(string);
void SetInt(int, int);
void SetInt(string, int);
这是可能的还是我对编译器的要求太多了?
因为 TryGet
本质上是一个 return 的值,所以选择 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;
}
问题已解决。