[英]type or namespace could be found - even though i declared the variable
i am getting this error: 我收到此错误:
The type or namespace name 'myObject' could not be found
找不到类型或名称空间名称“ myObject”
on this line: 在这条线上:
if (typeof(myObject) != typeof(String))
here is the surrounding code: 这是周围的代码:
for (int rCnt = 1; rCnt <= EmailList.Rows.Count; rCnt++)
{
object myObject = (EmailList.Cells[rCnt, 1] as Excel.Range).Value2;
if (typeof(myObject) != typeof(String))
continue;
cell = (string)(EmailList.Cells[ rCnt,1] as Excel.Range).Value2;
if (cell!=null)
emails.Add(cell.ToString());
}
what am i doing wrong? 我究竟做错了什么? i'm obviously declaring myObject.
我显然是在声明myObject。 thanks so much for your guidance.
非常感谢您的指导。
The typeof
operator takes a type identifier, not an instance identifier, as the argument. typeof
运算符将类型标识符而不是实例标识符用作参数。
You want myObject.GetType()
to get the type of an object: 您希望
myObject.GetType()
获取对象的类型:
if (myObject.GetType() != typeof(String))
Or even use the is
operator instead: 甚至使用
is
运算符代替:
if (!(myObject is String))
typeof
only works on a type name. typeof
仅适用于类型名称。
You want: 你要:
if (myObject.GetType() != typeof(String))
You can also use the is
operator: 您还可以使用
is
运算符:
if (!(myObject is String))
The difference only shows up when you are dealing with inheritance. 区别仅在您处理继承时显示。
DerivedInstance.GetType() == typeof(BaseType) // false
DerivedInstance is BaseType // true
As mentioned in comments, null
is an issue. 如评论中所述,
null
是一个问题。 If DerivedInstance
is actually null: 如果
DerivedInstance
实际上为null:
DerivedInstance.GetType() == typeof(BaseType) // NullReferenceException
DerivedInstance is BaseType // false
您需要myObject.GetType()或可以使用
if ((myObject as string)==null)
as BoltClock's a Unicorn mentioned, in this case you need GetType()
. 正如BoltClock提到的独角兽,在这种情况下,您需要
GetType()
。 In addition, the whole code you wrote is unnecessary. 另外,您编写的整个代码是不必要的。
object myObject = (EmailList.Cells[rCnt, 1] as Excel.Range).Value2;
if (typeof(myObject) != typeof(String)) // !(myObject is String) is enough. Plus, this won't work, if myObject is null.
continue;
cell = (string)(EmailList.Cells[ rCnt,1] as Excel.Range).Value2; // you can operate with myObject here as well
if (cell!=null) // in case of object having type, this is unnecessary.
emails.Add(cell.ToString()); // why calling ToString() on string?
the only thing you need is 您唯一需要的是
string str = (EmailList.Cells[rCnt, 1] as Excel.Range).Value2 as string;
if (str != null)
emails.add(str);
typeof is for types and not for instances , change it to typeof适用于类型而不是实例 ,请将其更改为
myObject.GetType()
Here are different solutions: 以下是不同的解决方案:
if (myObject.GetType() != typeof(String))
if (!(myObject is String))
if ((myObject as String)==null)
typeof takes a type as an argument. typeof将类型作为参数。 You've passed it an object instead.
您已将其传递给对象。 What you are probably trying to do is:
您可能想做的是:
if (myObject.GetType() != typeof(string))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.