C# 在使用 Action 时无法从用法中推断类型参数类型
C# can't infer type argument type from usage when using Action
假设我有针对 .Net 3.5 的 MonoDevelope 代码:
public void TestTemplate<T>(Action<T> action)
{
// pseudocode
m_funcDict[typeof(T).GetHashCode()] += action;
}
public void TestUsage(object arg)
{
TestTemplate(TestUsage);
}
我得到这样的错误:
Error CS0411: The type arguments for method
`TestTemplate(System.Action)' cannot be inferred from the usage.
Try specifying the type arguments explicitly (CS0411)
(Assembly-CSharp)
有没有什么方法可以在不手动指定类型参数的情况下做到这一点?
我要的只是automatically
推导类型
Is there any way I could do this without manual specify the type argument?
最短的答案是不,你不能。
类型推断不是这样工作的。您需要将方法 TestUsage
转换为适当的 Action 类型,以便将其用作 TestTemplate
.
的参数
但是在您的情况下,您可以使用 GetType()
在 运行 时从参数中提取 Type
并使用它来访问字典中的所需项目。
public void TestTemplate(Action<object> action,Type t)
{
// pseudocode
m_funcDict[t.GetHashCode()] += action;
}
public void TestUsage(object arg)
{
Type t = arg.GetType();
TestTemplate(TestUsage,t);
}
希望对您有所帮助
假设我有针对 .Net 3.5 的 MonoDevelope 代码:
public void TestTemplate<T>(Action<T> action)
{
// pseudocode
m_funcDict[typeof(T).GetHashCode()] += action;
}
public void TestUsage(object arg)
{
TestTemplate(TestUsage);
}
我得到这样的错误:
Error CS0411: The type arguments for method `TestTemplate(System.Action)' cannot be inferred from the usage. Try specifying the type arguments explicitly (CS0411) (Assembly-CSharp)
有没有什么方法可以在不手动指定类型参数的情况下做到这一点?
我要的只是automatically
推导类型
Is there any way I could do this without manual specify the type argument?
最短的答案是不,你不能。
类型推断不是这样工作的。您需要将方法 TestUsage
转换为适当的 Action 类型,以便将其用作 TestTemplate
.
但是在您的情况下,您可以使用 GetType()
在 运行 时从参数中提取 Type
并使用它来访问字典中的所需项目。
public void TestTemplate(Action<object> action,Type t)
{
// pseudocode
m_funcDict[t.GetHashCode()] += action;
}
public void TestUsage(object arg)
{
Type t = arg.GetType();
TestTemplate(TestUsage,t);
}
希望对您有所帮助