为什么以这种方式强制转换为类型不是有效的语法?
本文关键字:有效 语法 类型 方式强 转换 为什么 | 更新日期: 2023-09-27 18:06:04
编译器报错"as typeOfState",说找不到typeOfState。为什么会这样?有什么方法可以表达我想要完成的事情吗?
public static readonly IDictionary<Type, string> StateDictionary = new Dictionary<Type, string>
{
{typeof(SerializableDictionary<string, RadTabSetting>), "TabStates"},
{typeof(SerializableDictionary<string, RadPaneSetting>), "PaneStates"},
{typeof(SerializableDictionary<string, RadDockSetting>), "DockStates"},
{typeof(SerializableDictionary<string, RadDockZoneSetting>), "DockZoneStates"},
{typeof(SerializableDictionary<string, RadSplitterSetting>), "SplitterStates"},
{typeof(SerializableDictionary<string, RadSplitBarSetting>), "SplitBarStates"},
{typeof(SerializableDictionary<string, RadPageViewSetting>), "RadPageViewStates"},
{typeof(GlobalSettings), "GlobalSettings"},
};
foreach (var item in StateManager.StateDictionary)
{
string stateName = item.Value;
Type typeOfState = item.Key;
object stateSession = SessionRepository.Instance.GetSession(stateName) as typeOfState;
dataToSave.Add(stateName, stateSession);
}
欢呼编辑:好的。要明白不能将变量用作类型,即使变量的类型是"type"
我有什么选择?这里是完整的源代码:
[WebMethod]
public static bool Export()
{
bool successful = false;
try
{
HttpContext.Current.Request.ContentType = "text/xml";
HttpContext.Current.Response.Clear();
SerializableDictionary<string, object> dataToSave = new SerializableDictionary<string, object>();
foreach (var item in StateManager.StateDictionary)
{
string stateName = item.Value;
Type typeOfState = item.Key;
object stateSession = SessionRepository.Instance.GetSession(stateName);
dataToSave.Add(stateName, stateSession);
}
XmlSerializer serializer = new XmlSerializer(dataToSave.GetType());
serializer.Serialize(HttpContext.Current.Response.OutputStream, dataToSave);
successful = true;
}
catch (Exception exception)
{
_logger.ErrorFormat("Unable to serialize session. Reason: {0}", exception.Message);
}
return successful;
}
不能将Type
对象与as
关键字一起使用。查看文档以确保其正确使用。
要完成我认为你正在尝试做的事情,也许可以查看Convert.ChangeType
[MSDN].
typeOfState
是Type
类型的对象,它不是type。如果你想做你正在尝试的事情,你需要以某种方式使用泛型。
因为typeOfState是一个变量而不是类型。必须向as操作符传递编译时已知的类型。
语法为expr as T
,其中T
将指向引用类型的名称(例如classname)。T
不是一个通用表达式——也就是说,它不能是一个变量名或一个表示类型的值(即使它是一个Type
对象)。
编译器错误信息应该这样指示about。
快乐编码。