[英]Cannot assign <null> to an implicitly-typed local variable
I want to to select a field from Data table dt_branches_global
in such a way that, if radioButton_QP
is Checked then the Data table will contain a string
field otherwise the Data Table contain an int
field. 我想从数据表
dt_branches_global
中选择一个字段,如果radioButton_QP
是Checked,那么Data表将包含一个string
字段,否则数据表包含一个int
字段。 This is what I am doing. 这就是我在做的事情。 But I am getting error while initializing the variable Var.
但是我在初始化变量Var时遇到错误。
var AllBranch_IDs = null;
if (radioButton_QP.Checked == true)
AllBranch_IDs = dt_branches_global.AsEnumerable().Select(x => x.Field<string>("BusinessSectorID")).ToArray();
else
AllBranch_IDs = dt_branches_global.AsEnumerable().Select(x => x.Field<int>("BusinessSectorID")).ToArray();
The compiler is still strongly typed so it needs to figure out the type. 编译器仍然是强类型的,因此需要确定类型。 It is impossible for the compiler to infer the type of you assign it to null.
编译器无法推断您将其分配为null的类型。 Then you later on try to assign it to two different types.
然后你尝试将它分配给两种不同的类型。 An array of ints and an array of strings.
一个int数组和一个字符串数组。
Try something like: 尝试类似的东西:
string[] AllBranch_IDs = null;
if (radioButton_QP.Checked == true)
AllBranch_IDs = dt_branches_global.AsEnumerable().Select(x => x.Field<string>("BusinessSectorID")).ToArray();
else
AllBranch_IDs = dt_branches_global.AsEnumerable().Select(x => x.Field<int>("BusinessSectorID").ToString()).ToArray();
As it stands, the type cannot be inferred from null
- null
could be any reference type. 就目前而言,无法从
null
推断出类型 - null
可以是任何引用类型。
ie The problem here 即问题在这里
var AllBranch_IDs = null;
is that the compiler would need to scan to the following lines of code to deduce the type of AllBranch_IDs
(which isn't possible in C# anyway), and wouldn't work due to the dynamic nature of the type - you assign it either IEnumerable<string>
or IEnumerable<int>
). 是编译器需要扫描到以下代码行来推断
AllBranch_IDs
的类型(无论如何都不可能在C#中),并且由于类型的动态特性而无法工作 - 您可以将其分配给IEnumerable<string>
或IEnumerable<int>
)。
You could use IEnumerable<object>
and then box the ints: 您可以使用
IEnumerable<object>
,然后将ints包装:
eg: 例如:
IEnumerable<object> AllBranch_IDs = null;
if (new Random().Next(10) > 5)
{
AllBranch_IDs = new [] {1,2,3,4}.Cast<object>().ToArray();
}
else
{
AllBranch_IDs = new [] {"hello", "world"}.ToArray();
}
Declaring it as dynamic
would also compile, viz dynamic AllBranch_IDs = null
, although the consumer of the result would need to be aware that the type is dynamic. 将其声明为
dynamic
也可以编译,即dynamic AllBranch_IDs = null
,尽管结果的使用者需要知道该类型是动态的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.