gpt4 book ai didi

c# - 为什么以这种方式转换为类型不是有效语法?

转载 作者:太空宇宙 更新时间:2023-11-03 19:28:00 25 4
gpt4 key购买 nike

编译器提示“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 关键字一起使用。检查documentation正确使用。

要完成我认为您正在尝试做的事情,也许可以查看 Convert.ChangeType [ MSDN ]

关于c# - 为什么以这种方式转换为类型不是有效语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7127304/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com