2

推奨されるベスト プラクティスは、アプリケーションのスレッドの現在のカルチャを設定して、リソース ルックアップで正しい言語を使用できるようにすることです。

残念ながら、これは他のスレッドのカルチャを設定しません。これは、特にスレッド プール スレッドの問題です。

問題は、最小限の余分な配管コードで、文字列リソース ルックアップをスレッド プール スレッドから正しくローカライズできるように設定するにはどうすればよいかということです。


編集:

問題は、文字列テーブルから生成されるこのコードです。

internal static string IDS_MYSTRING {
    get {
        return ResourceManager.GetString("IDS_MYSTRING", resourceCulture);
    }
}

この場合の「resourceCulture」は、スレッド プール スレッドに対して正しく設定されていません。「ResourceManager.GetString("IDS_MYSTRING", correctCulture);」を呼び出すだけです。しかし、それは文字列が存在することをコンパイル時にチェックする利点を失うことを意味します。

文字列テーブルの可視性を public に変更し、リフレクションを使用して列挙されたすべてのアセンブリの Culture プロパティを設定することで修正できるかどうか疑問に思っています。

4

4 に答える 4

2

将来これを試みる人のために、私は次のコードになってしまいました:

/// <summary>
/// Encapsulates the culture to use for localisation.
/// This class exists so that the culture to use for
/// localisation is defined in one place.
/// Setting the Culture property will change the culture and language
/// used by all assemblies, whether they are loaded before or after
/// the property is changed.
/// </summary>
public class LocalisationCulture
{
    private CultureInfo                 cultureInfo         = Thread.CurrentThread.CurrentUICulture;
    private static LocalisationCulture  instance            = new LocalisationCulture();
    private List<Assembly>              loadedAssemblies    = new List<Assembly>();
    private static ILog                 logger              = LogManager.GetLogger(typeof(LocalisationCulture));
    private object                      syncRoot            = new object();

    private LocalisationCulture()
    {
        AppDomain.CurrentDomain.AssemblyLoad += new AssemblyLoadEventHandler(this.OnAssemblyLoadEvent);

        lock(this.syncRoot)
        {
            foreach(Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                if(LocalisationCulture.IsAssemblyResourceContaining(assembly))
                {
                    this.loadedAssemblies.Add(assembly);
                }
            }
        }
    }

    /// <summary>
    /// The singleton instance of the LocalisationCulture class.
    /// </summary>
    public static LocalisationCulture Instance
    {
        get
        {
            return LocalisationCulture.instance;
        }
    }

    /// <summary>
    /// The culture that all loaded assemblies will use for localisation.
    /// Setting the Culture property will change the culture and language
    /// used by all assemblies, whether they are loaded before or after
    /// the property is changed.
    /// </summary>
    public CultureInfo Culture
    {
        get
        {
            return this.cultureInfo;
        }

        set
        {
            // Set the current culture to enable resource look ups to
            // use the correct language.

            Thread.CurrentThread.CurrentUICulture = value;

            // Store the culture info so that it can be retrieved
            // elsewhere throughout the applications.

            this.cultureInfo = value;

            // Set the culture to use for string look ups for all loaded assemblies.

            this.SetResourceCultureForAllLoadedAssemblies();
        }
    }

    private static bool IsAssemblyResourceContaining(Assembly assembly)
    {
        Type[] types = assembly.GetTypes();

        foreach(Type t in types)
        {
            if(     t.IsClass
                &&  t.Name == "Resources")
            {
                return true;
            }
        }

        return false;
    }

    private void OnAssemblyLoadEvent(object sender, AssemblyLoadEventArgs args)
    {
        if(!LocalisationCulture.IsAssemblyResourceContaining(args.LoadedAssembly))
        {
            return;
        }

        lock(this.syncRoot)
        {
            this.loadedAssemblies.Add(args.LoadedAssembly);

            this.SetResourceCultureForAssembly(args.LoadedAssembly);
        }
    }

    private void SetResourceCultureForAllLoadedAssemblies()
    {
        lock(this.syncRoot)
        {
            foreach(Assembly assembly in this.loadedAssemblies)
            {
                this.SetResourceCultureForAssembly(assembly);
            }
        }
    }

    private void SetResourceCultureForAssembly(Assembly assembly)
    {
        Type[] types = assembly.GetTypes();

        foreach(Type t in types)
        {
            if(     t.IsClass
                &&  t.Name == "Resources")
            {
                LocalisationCulture.logger.Debug(String.Format( CultureInfo.InvariantCulture,
                                                                "Using culture '{0}' for assembly '{1}'",
                                                                this.cultureInfo.EnglishName,
                                                                assembly.FullName));

                PropertyInfo propertyInfo = t.GetProperty(  "Culture",
                                                            BindingFlags.GetProperty | BindingFlags.Static | BindingFlags.NonPublic);

                MethodInfo methodInfo = propertyInfo.GetSetMethod(true);

                methodInfo.Invoke(  null,
                                    new object[]{this.cultureInfo} );

                break;
            }
        }
    }
}
于 2009-10-19T10:42:06.987 に答える
1

insert... resx ファイルとサテライト アセンブリの文字列リソースを使用しています。ファイルに正しい名前を付けていますか?

Resource1.resx:

<!-- snip-->
<data name="foo" xml:space="preserve">
    <value>bar</value>
  </data>

Resource1.FR-fr.resx

<--! le snip -->
  <data name="foo" xml:space="preserve">
    <value>le bar</value>
  </data>

Class1.cs :

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Threading;

namespace Frankenstein
{
    public class Class1
    {



        struct LocalizedCallback
        {
            private WaitCallback localized;

            public LocalizedCallback(WaitCallback user)
            {
                var uiCult = Thread.CurrentThread.CurrentUICulture;

                // wrap
                localized = (state) =>
                {
                    var tp = Thread.CurrentThread;
                    var oldUICult = tp.CurrentUICulture;
                    try
                    {
                        // set the caller thread's culture for lookup
                        Thread.CurrentThread.CurrentUICulture = uiCult;

                        // call the user-supplied callback
                        user(state);
                    }
                    finally
                    {
                        // let's restore the TP thread state
                        tp.CurrentUICulture = oldUICult;
                    }
                };

            }

            public static implicit operator WaitCallback(LocalizedCallback me)
            {
                return me.localized;
            }
        }

        public static void Main(string[] args)
        {

            AutoResetEvent evt = new AutoResetEvent(false);
            WaitCallback worker = state =>
            {
                Console.Out.WriteLine(Resource1.foo);
                evt.Set();
            };

            // use default resource
            Console.Out.WriteLine(">>>>>>>>>>{0}", Thread.CurrentThread.CurrentUICulture);
            Console.Out.WriteLine("without wrapper");
            ThreadPool.QueueUserWorkItem(worker);
            evt.WaitOne();
            Console.Out.WriteLine("with wrapper");
            ThreadPool.QueueUserWorkItem(new LocalizedCallback(worker));
            evt.WaitOne();

            // go froggie
            Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("FR-fr");
            Console.Out.WriteLine(">>>>>>>>>>{0}", Thread.CurrentThread.CurrentUICulture);           
            Console.Out.WriteLine("without wrapper");
            ThreadPool.QueueUserWorkItem(worker);
            evt.WaitOne();
            Console.Out.WriteLine("with wrapper");
            ThreadPool.QueueUserWorkItem(new LocalizedCallback(worker));
            evt.WaitOne();
        }
    }
}

出力:

>>>>>>>>>>en-US
without wrapper
bar
with wrapper
bar
>>>>>>>>>>fr-FR
without wrapper
bar
with wrapper
le bar
Press any key to continue . . .

これが機能する理由は、Resource1.Culture プロパティが常に null に設定されているため、デフォルト (IE Thread.CurrentThread.UICulture) にフォールバックするためです。

それを証明するには、Resource1.Designer.cs ファイルを編集し、クラスから次の属性を削除します。

//[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]

次に、Resource.Culture プロパティ アクセサーと foo プロパティ アクセサーにブレークポイントを設定し、デバッガーを起動します。

乾杯、フロリアン

于 2009-10-07T11:54:08.683 に答える
0

Thread.CurrentThread.CurrentCultureの代わりにApplication.CurrentCultureにアクセスしてみましたか?

于 2009-10-07T12:23:46.030 に答える