c#“为"对比“()"转换 [英] c# "as" vs "()" conversion

查看:64
本文介绍了c#“为"对比“()"转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这种情况下,为什么会编译兼容引用类型之间的转换(Excel 2010,.Net 4.5)

Why the conversions between compatible reference types will compile (Excel 2010, .Net 4.5) in this case

using Excel = Microsoft.Office.Interop.Excel;
Excel.Application excelApplication = null;
excelApplication = new Excel.Application();

Excel.Worksheet worksheet = workbook.Worksheets[1] as Excel.Worksheet;

在下面的情况下不会,尽管我看到这样显示的示例:

and in the case below it will not, although I saw exampales shown like that:

Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets[1];

在这种情况下,我收到以下编译错误:

In this case I get the following compiling error :

> CSC : error CS0518: Predefined type 'Microsoft.CSharp.RuntimeBinder.Binder' is not 
defined or imported

> error CS1969: One or more types required to compile a dynamic expression cannot be 
found. Are you missing a reference?

最好

编辑:感谢下面的两个回答者,听起来很合理:

EDIT : Thanks to the both answerer below the following explanation sounds reasonable:

在.NET版本> = 4.0的项目的项目参考中不包含Microsoft.CSharp,支持 动态语言运行时(DLR)和C#之间的相互操作不是 ,即无法进行动态投射.

without including Microsoft.CSharp in the Project References for projects with .Net Version >= 4.0, support for inter operation between the Dynamic Language Runtime (DLR) and C# is not possible, i.e. no dynamic cast is possible.

推荐答案

(T)如果无法将x强制转换为T,则x将抛出InvalidCastException异常,而在这种情况下x作为T将返回null.当没有类型转换问题时,两者是等效的.

(T) x will throw an InvalidCastException exception if x cannot be casted to T, whereas x as T will return null in this case. When there is no type casting problem the two are equivalent.

(T)x是比x作为T更简单,更快速的操作. 要获得性能结果,请查看: http://www.codeproject.com /Articles/8052/Type-casting-impact-over-execution-performance-in#_rating

(T) x is a simpler and faster operation than x as T. For performance results have a look at : http://www.codeproject.com/Articles/8052/Type-casting-impact-over-execution-performance-in#_rating

一些其他信息:

强制类型转换显式调用从一种类型到另一种类型的转换运算符.如果未定义此类转换运算符,则转换将失败.您可以编写自定义转换运算符以在用户定义的类型之间进行转换.有关定义转换运算符的更多信息,请参见显式(C#参考)和隐式(C#参考).

A cast explicitly invokes the conversion operator from one type to another. The cast will fail if no such conversion operator is defined. You can write custom conversion operators to convert between user-defined types. For more information about defining a conversion operator, see explicit (C# Reference) and implicit (C# Reference).

来源: http://msdn.microsoft .com/en-us/library/ms173105(v = vs.80).aspx

更新:鉴于您提供的错误消息,该应用程序似乎以ASP.NET 3.5为目标.我的猜测是转到项目属性并将目标框架设置为4.0将解决此问题.

UPDATE: Given the error messages you provided, it seems likely that the application is targeting ASP.NET 3.5. My guess is that going to the project properties and setting the target framework to 4.0 will solve the issue.

这篇关于c#“为"对比“()"转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆