[英]Extension methods not working for int?
public static class NumberExtensions
{
static string Format(this int integer) // Write one for int too, just incase :')
{
return string.Format("{0:n0}", integer);
}
}
Calling the following code tells me the method Format
doesn't exist. 调用以下代码可以告诉我
Format
方法不存在。
idItemsFinished.Format()
Here is the variable 这是变量
var idItemsFinished = Program.IdItemsProcessed;
It's simply just an int. 这只是一个整数。
public int IdItemsProcessed;
Adding a public access specifier to the extension method should fix the issue. 在扩展方法中添加公共访问说明符应该可以解决此问题。
public static class NumberExtentions
{
public static string Format(this int integer)
{
return string.Format("{0:n0}", integer);
}
}
To answer the question in the subject - yes, extension methods do work on int
, there's nothing special about int
. 要回答这个问题的问题-是的,扩展方法做工作,
int
,有没有什么特别的int
。 In fact, they'll work on integer literals as well - 5.Format()
should work fine. 实际上,它们也可以处理整数文字
5.Format()
应该可以正常工作。
You've left out what I suspect is the reason for your problem, which is namespaces. 您遗漏了我怀疑是您的问题的原因,这就是名称空间。 There might be dozens of places in your code and especially your dependent libraries that add extension methods to
int
and you don't want to necessarily import them all (leading to potential conflicts), so you have to add a using
statement to your code that points to the namespace of NumberExtentions
. 您的代码中可能有很多地方,尤其是您的从属库中,它们向
int
添加了扩展方法,并且您不想全部导入它们(导致潜在的冲突),因此您必须在代码中添加using
语句,指向NumberExtentions
的命名空间。
This is no different than adding a reference to a class, except that Visual Studio's intellisense is usually pretty good in highlighting an unknown class and offering to add a using
for it for you, but it won't be as helpful with extension methods. 这与添加对类的引用没有什么不同,除了Visual Studio的intellisense通常在突出显示未知类并为您提供
using
目的方面相当不错,但是对扩展方法没有帮助。
Simply add a using statement and you'll probably be good to go. 只需添加一个using语句,您可能会很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.