Passing the parameter

你。 提交于 2019-12-24 06:33:43

问题


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?


回答1:


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




回答2:


var is used for type inference, not to declare a dynamic variable. Use the actual input type as the type for inp.




回答3:


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 to listview1.itemsource.




回答4:


As others have said, you're mixing implicitly typed variables (type inference), and an explictly typed function signature.

What you should have is:

var Input = txtQuestion.text; // Implicitly typed variable of type string
listview1.itemsource = getinput(Input); 

// Strongly typed method taking string, returning List<answers> 
public List<answers>getinput(string question) 
{ 
    var result = new List<answers>();
    result.Add(answer);
    return result; 
} 

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.




回答5:


var is just used in the JavaScript code as a variant. If you are using var then you can use string or use object.

public void getinput(object inp) 
{ 
    ................ 
    .................. 
} 


public void getinput(string inp) 
{ 
    ................ 
    .................. 
} 



回答6:


public void getinput(object inp)
{
................
..................
}

As soon as C# is strongly-typed language, the compiler always knows, what real type your variable belongs to:

var Input = ....

Type of .... is always known. That's why you can't declare

var a;

and this is EXACLTLY what you are trying to do in

public void getinput(var inp)
{
    ................
    ..................
}



回答7:


Use object in the function instead of var. Then cast it to the appropriate type within the function.



来源:https://stackoverflow.com/questions/3726446/passing-the-parameter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!