I have a problem with the var
keyword
I have defined it like this at the form load
public partial class form1 :form
{
public var a;
private void form1_load(object sender, eventargs e)
{
// i have used "a" like this....
a = abc.members blahhhh blahhhhh
bindingsource1.datasource = a;
datagridview1.datasource = bindingsource1;
}
}
but I got the error on this line
public Var a;
the type or namespace name 'var' co开发者_JS百科uld not be defined
Can I define public class varaible so that I can access this all methods in that class?
var
in C# is different from var
in other languages; in C# you use var
to have the compiler determine the type of a certain local variable for you, but you cannot use it to declare fields/properties.
You have to specify the actual type instead. I have no idea what a
is, so I can't tell you what type to use.
You have to use the concrete type instead of var - for example "string", "int", ...
This is because "var" is only syntactic suggar. The compliler interferes the concrete type and insert it instead of var. In your case this is impossible, because the compiler won't look so far as the form_load - it just looks at the expression after the "="
As a side note: you should not define fields as public. Make them private and define public accessors or public propertys for them. In this way you don't leak internal implementation details to the outside world and got no problems if you want to change this implementation-details later on.
If you want to make it a public (and not a local) variable you have to declare it as a specific type, for example 'string', 'int' or a selfwritten class
variables having an implicit type var must be declared at method scope.
public int a;
would suffice, i suppose.
As per, http://msdn.microsoft.com/en-us/library/bb383973.aspx
Only variables that are declared at method scope can have an implicit type var
As you need this for a linq query, you can assign the explicitly typed public variables wherever (inside a function) you run the query. For example,
func()
{
var results = from p1 in phones where p1.name="abc";
MyPublicVariable = results;
}
Where MyPublicVariable could be an enumerable.
精彩评论