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

标签 c#

编译器提示“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/

相关文章:

c# - 如何捕获 WCF 服务激活异常?

c# - 如何以编程方式检查 C++ DLL 文件和 C# DLL 文件的引用以调试 DLLS 以自动执行测试过程

c# - 在 C# 中派生静态类

c# - 将字符串中的特殊字符转换为 Unicode 十六进制代码?

c# - NSwag 自定义 JSON 输出

c# - Azure 函数无法访问 mscorelib.dll 访问被拒绝

c# - 是否可以获取当前事件应用程序的名称

c# - 在窗口登录屏幕上运行应用程序

c# - .NET 序列化排序

c# - WPF - 删除启动后自动运行的应用程序