C# CodeGeneration 变量作为类型
,生成代码来执行强制转换,如下所示:(类型也是生成的类,我提供了一个仅包含 object
和 string
的示例)
object o;
string s = (string)o;
在现有应用程序中 类型为 int
,则抛出 InvalidCastException
。因此,我想将代码更改为:
object o;
string s = o as string;
并稍后检查 string s
是否为 null。
System.CodeDom
用于执行代码生成。转换是使用 CodeCastExpression 类生成的。
我找不到生成变量作为类型
的方法...有人可以帮助我吗?谢谢!
In an existing application, code is generated to perform a cast, like below: (the types are also generated classes, I provide an example with just object
and string
)
object o;
string s = (string)o;
When o is of type int
, an InvalidCastException
is thrown. Therefore, I want to change the code into:
object o;
string s = o as string;
and check later on whether string s
is null.
The System.CodeDom
is used to perform the code generation. The cast is generated using the CodeCastExpression
Class.
I cannot find a way to generate the variable as type
way... Can someone help me out? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 System.ComponentModel.TypeConverter 怎么样?
Type) 的方法,并具有“通用”ConvertTo 方法,该方法接受对象并返回对象:
它具有检查是否
CanConvertFrom(Type)
和CanConvertTo ( 看这里: http://msdn.microsoft.com/en -us/library/system.componentmodel.typeconverter.aspx
What about using
System.ComponentModel.TypeConverter
.It has methods to check whether it
CanConvertFrom(Type)
andCanConvertTo(Type)
and has the "universal" ConvertTo Method which accepts an Object in and gives an Object back:Have a look here: http://msdn.microsoft.com/en-us/library/system.componentmodel.typeconverter.aspx
也许你想尝试这个:
也许你可以在前面放一个 if 语句,这样代码就会显示:
这仅适用于非值类型。有关如何实现“is”的信息,请参阅这篇文章操作员。
Maybe you want to try this instead:
Maybe you can just put an if statement before so the code would read:
This will only work with non-value-types. See this post for information on how to accomplish the "is" operator.
问题是,“as”运算符不能与非引用类型一起使用。
例如:
这应该适用于大多数情况。您可以执行从任何对象到另一种引用类型的 as 转换。
The problem is, the 'as' operator cannot be used with a non reference type.
For example:
This should work for most of it. You can do the as conversion from any object to another reference type.