【问题标题】:C# can't infer type argument type from usage when using Action使用 Action 时,C# 无法从用法中推断类型参数类型
【发布时间】:2016-09-05 21:35:28
【问题描述】:

假设我有这样的代码,MonoDevelope 以 .Net 3.5 为目标:

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) (Assembly-CSharp)

有没有什么方法可以在不手动指定类型参数的情况下做到这一点?

我想要的只是automatically推断类型。

【问题讨论】:

  • 我需要在TestTemplate 函数中对T 做一些事情。确实我想用这种方式来提取TestUsage的参数信息
  • 我添加了一些伪代码来解释我的目的。
  • 你为什么要typeof(T).GetHashCode()?确定typeof(T) 是合适的键吗?
  • @Enigmativity 之类的。这只是一个伪代码来解释我想用 T 做点什么。
  • 为什么不想指定类型呢? TestTemplate&lt;object&gt;(TestUsage); 看起来很简单。或者您可以将 TestUsage 本身设为通用。

标签: c# unity3d monodevelop


【解决方案1】:

有没有什么方法可以在不手动指定类型参数的情况下做到这一点?

最短的答案是不,你不能

类型推断不是这样工作的。您需要将方法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);
}

希望对你有帮助

【讨论】:

  • 感谢您的提示。我以后可能会尝试这种方式。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-06
  • 1970-01-01
相关资源
最近更新 更多