无法从用法推断方法的类型参数
namespace TestLibrary
{
[TestFixture]
public class Class1
{
public delegate T Initializer<T>();
public static T MyGenericMethod<T>(Initializer<T> initializer) where T : class
{
return initializer != null ? initializer() : null;
}
[Test]
public void Test()
{
var result = MyGenericMethod(MyInitializer);
Assert.IsNotNull(result);
}
private object MyInitializer()
{
return new object();
}
}
}
这是在 Visual Studion 2010 中运行时的一段功能代码。如果我尝试从命令行使用 MSBUILD 构建它......
"c:\Windows\Microsoft.NET\Framework\v3.5\MSBuild.exe" Solution1.sln
我会收到非常熟悉的错误消息:
无法推断方法“方法名称”的类型参数 的用法。尝试显式指定类型参数。
有什么想法吗?
namespace TestLibrary
{
[TestFixture]
public class Class1
{
public delegate T Initializer<T>();
public static T MyGenericMethod<T>(Initializer<T> initializer) where T : class
{
return initializer != null ? initializer() : null;
}
[Test]
public void Test()
{
var result = MyGenericMethod(MyInitializer);
Assert.IsNotNull(result);
}
private object MyInitializer()
{
return new object();
}
}
}
This is a functioning piece of code when running in Visual Studion 2010. If I try to build this using MSBUILD from command line...
"c:\Windows\Microsoft.NET\Framework\v3.5\MSBuild.exe" Solution1.sln
... I get very familiar error message:
The type arguments for method 'Method name' cannot be inferred from
the usage. Try specifying the type arguments explicitly.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这似乎是 VS 2010 和 MSBuild 3.5 使用的编译器版本之间的差异。这是有道理的,因为类型推断在后来的编译器版本中得到了很大的改进。
如果需要使用 MSBuild 3.5,则需要更正代码:
var result = MyGenericMethod
但是,您应该能够使用 MSBuild v4 并以 3.5 框架为目标。您还可以在 VS 2010 中以该框架为目标。基于使用 VS 2010 以 3.5 为目标时代码编译的事实,我认为它可能会通过 MSBuild v4 工作。
由评论中的 Radex 提供:
c:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe" Solution1.sln /p:TargetFrameworkVersion=v3.5
只是为了澄清一下,这是我的有教养的猜测基于评论的答案
不确定这是否相关,但我在 MSDN 上找到了这个:http://msdn.microsoft.com/en-us/library/ee855831.aspx
进一步阅读:
http://togaroga.com/2009/11/smarter-type-使用-c-4 进行推理/
This appears to be a difference between the compiler versions used by VS 2010 and MSBuild 3.5. This makes sense as type inference was improved a lot in later compiler versions.
If you need to use MSBuild 3.5, you'll need to correct your code:
var result = MyGenericMethod<object>(MyInitializer);
However, you should be able to use MSBuild v4 and target the 3.5 framework. You can also target this framework in VS 2010. Based on the fact that when targeting 3.5 using VS 2010 the code compiles, I think it will likely work via MSBuild v4.
Courtesy of Radex in the comments:
c:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe" Solution1.sln /p:TargetFrameworkVersion=v3.5
Just to clarify, this is my educated-guess answer based on the comments.
Not sure if this is relevant, but I found this on MSDN: http://msdn.microsoft.com/en-us/library/ee855831.aspx
Further reading:
http://togaroga.com/2009/11/smarter-type-inference-with-c-4/