开发者

Passing the parameter

开发者 https://www.devze.com 2023-01-16 04:38 出处:网络
I am passing the parameter to the function as a var type. It is not a开发者_如何学Goccepting, how do I pass to the function?

I am passing the parameter to the function as a var type. It is not a开发者_如何学Goccepting, 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?


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 is used for type inference, not to declare a dynamic variable. Use the actual input type as the type for inp.


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.


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.


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) 
{ 
    ................ 
    .................. 
} 


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)
{
    ................
    ..................
}


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

0

精彩评论

暂无评论...
验证码 换一张
取 消