实例是只读异常,而在asp.net中更改区域性 [英] Instance is read-only Exception while changing culture in asp.net

查看:75
本文介绍了实例是只读异常,而在asp.net中更改区域性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在用户能够更改语言,日期格式等的地方实现多文化应用程序.我编写了core,但是它返回Exception: System.InvalidOperationException:实例为只读.

I try to implement multicultural application where users able to change language, date format and etc. I wrote core but it returns Exception: System.InvalidOperationException: Instance is read-only.

switch (culture)
    {
        case SystemCulture.English:
                Thread.CurrentThread.CurrentCulture = new CultureInfo(CultureCodes.English);
                Thread.CurrentThread.CurrentUICulture = new CultureInfo(CultureCodes.English);
                break;
                        //another cultures here
    }
    switch (cultureFormat)
    {
        case SystemDateFormat.European:
                  var europeanDateFormat = CultureInfo.GetCultureInfo(CultureCodes.Italian).DateTimeFormat;
                  Thread.CurrentThread.CurrentCulture.DateTimeFormat = europeanDateFormat;
                  Thread.CurrentThread.CurrentUICulture.DateTimeFormat = europeanDateFormat;
                  break;
    //another cultures here
    }
        

我在互联网上找到了一些信息,我必须使用我所在文化的新实例对象,我更改了代码,只是添加了以下内容:

I found some information on internet and i have to use new instance object of my culture, i changed my code just adding:

CultureInfo myCulture;

switch (culture)
{
       case SystemCulture.English:
            myCulture= new CultureInfo(CultureCodes.English);
            break;
}

下面是开关,下面是波纹管:

and bellow, out of switch :

Thread.CurrentThread.CurrentCulture = cultureInfo;

我对线程不熟悉,不确定我使用的是否正确.你能建议我如何正确地做到这一点吗?

I'm not familiar with Threads and i'm not sure if i used is correctly. Could you please suggest me how to do this it right way ?

推荐答案

您收到 Instance is read-only 错误,因为您试图通过下面的代码.

You get the Instance is read-only error because you are trying to alter a property on a a read-only culture, via the code below.

Thread.CurrentThread.CurrentCulture.DateTimeFormat = europeanDateFormat;

您可以通过其 IsReadOnly 属性检查区域性是否为只读;内置的是.

You can check whether a culture is readonly via its IsReadOnly property; the built-in ones are.

相反,您必须对当前活动的区域性进行克隆/复制,在该克隆上进行任何更改,然后将其分配给的 CurrentCulture 和/或 CurrentUICulture 当前线程.

Instead, you must make a clone/copy of the currently active culture, apply any changes on that clone and assign that one to the CurrentCulture and/or CurrentUICulture of the current thread.

var clone = Thread.CurrentThread.CurrentCulture.Clone() as CultureInfo;
clone.DateTimeFormat = CultureInfo.GetCultureInfo("it").DateTimeFormat;

Thread.CurrentThread.CurrentCulture = clone;
Thread.CurrentThread.CurrentUICulture = clone; 

这篇关于实例是只读异常,而在asp.net中更改区域性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆