public void TestTemplate<T>(Action<T> action) { // pseudocode m_funcDict[typeof(T).GetHashCode()] += action; } public void TestUsage(object arg) { TestTemplate(TestUsage); }
我得到了这样的错误:
错误CS0411:方法的类型参数 `无法根据用法推断TestTemplate(System.Action)“”。 尝试显式指定类型参数(CS0411) (组件CSharp)
我想要的只是 automatically 推断类型。
automatically
最简短的回答是 不,你不能 .
类型推断不是这样工作的。你需要转换方法 TestUsage 适当的Action类型,以便将其用作的参数 TestTemplate .
TestUsage
TestTemplate
但在您的情况下,您可以使用 GetType() Type 在运行时从参数访问,并使用它访问字典中所需的项。
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); }
希望能有所帮助