传递参数
我将参数作为 var 类型传递给函数。它不接受,我如何传递给该函数?
示例
var Input = ................
listview1.itemsource = getinput(Input);
public List<answers>getinput(var inp)
{
................
..................
}
这里函数不接受 var
。我能做些什么?
I am passing the parameter to the function as a var
type. It is not accepting, how do I pass to the function?
Example
var Input = ................
listview1.itemsource = getinput(Input);
public List<answers>getinput(var inp)
{
................
..................
}
Here the function is not accepting the var
. What can I do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
var只能在同一个语句中声明和初始化局部变量时使用;该变量不能初始化为 null、方法组或匿名函数。
MSDN:隐式类型局部变量
var can only be used when a local variable is declared and initialized in the same statement; the variable cannot be initialized to null, or to a method group or an anonymous function.
MSDN : Implicitly Typed Local Variables
var
用于类型推断,而不是声明动态变量。使用实际输入类型作为inp
的类型。var
is used for type inference, not to declare a dynamic variable. Use the actual input type as the type forinp
.它不接受第三行,因为您的函数属于
void
类型,并且您尝试将该函数的结果分配给listview1.itemsource
。It's not accepting the third line because your function is of the type
void
and you try to assign the result of that function tolistview1.itemsource
.正如其他人所说,您正在混合隐式类型变量(类型推断)和显式类型函数签名。
您应该拥有的是:
抱歉,如果这与您的代码不完全匹配,但它应该演示您所追求的内容。
var 关键字用于从赋值运算符的右侧推断变量的类型。在方法的签名中,没有赋值运算符,因此无法进行推理。此外,您始终可以传递任意数量的从基类派生的类型,这将使编译器难以确定参数的正确类型。 (您是指 DbReader、SqlDbReader 还是 IDbReader?)
可以推断变量。参数不能。
As others have said, you're mixing implicitly typed variables (type inference), and an explictly typed function signature.
What you should have is:
Sorry if this doesn't exactly match your code, but it should demonstrate what you're after.
The var keyword is used to infer the type of a variable from the right-hand side of the assignment operator. In a method's signature, there's no assignment operator, so inference can't take place. Further, you could always pass any number of types derived from a base class, which would make it difficult for the compiler to determine the correct type of the argument. (Did you mean DbReader, SqlDbReader, or IDbReader?)
Variables can be inferred. Parameters cannot.
var
只是在 JavaScript 代码中用作变体。如果您使用var
那么您可以使用字符串或使用对象。var
is just used in the JavaScript code as a variant. If you are usingvar
then you can use string or use object.只要 C# 是强类型语言,编译器就始终知道您的变量属于什么实际类型:
.... 的类型始终是已知的。这就是为什么你不能声明
,而这正是你想要做的
As soon as C# is strongly-typed language, the compiler always knows, what real type your variable belongs to:
Type of .... is always known. That's why you can't declare
and this is EXACLTLY what you are trying to do in
在函数中使用
object
而不是var
。然后将其转换为函数内适当的类型。Use
object
in the function instead ofvar
. Then cast it to the appropriate type within the function.