我在下面简单的c#方法中有一个简单的强制转换问题
using System;
using System.Data.SqlTypes;
...
private void method1() {
string s = "TestString";
object o = s;
SqlString t1 = (SqlString) s;
SqlString t2 = (SqlString) o;
}
...
Run Code Online (Sandbox Code Playgroud)
当直接从s
(在t1的情况下)投射时,我没有得到任何错误但是当o
我从中获得异常时:
指定演员表无效.
我有同样的问题转换object
为所有类型System.Data.SqlTypes
我怎样才能将其中的object
字符串强制转换为SqlString
?
回答你的问题
private void method1() {
object o = "MyString";
SqlString t1 = o as String
}
Run Code Online (Sandbox Code Playgroud)
如果 o 不是字符串,则 t1 将为 null。