Работа с текущим языком: лучшая альтернатива этому коду? - PullRequest
0 голосов
/ 23 мая 2019

(я действительно не знал, как правильно озаглавить этот пост)

У вас, ребята, есть лучшая альтернатива этому коду?Я чувствую, что могу достичь большего с помощью словаря в сочетании с моим классом JsonSerialized.

WillyTC config = new WillyTC();
            switch (GetCurrentLanguage().ToLower())
            {
                case "french":
                    PerimetreExterne = GetSolidworksProp(config.PerimetreExterne_Fr);
                    PerimetreInterne = GetSolidworksProp(config.PerimetreInterne_Fr);

                    break;
                case "english":
                    PerimetreExterne = GetSolidworksProp(config.PerimetreExterne_En);
                    PerimetreInterne = GetSolidworksProp(config.PerimetreInterne_En);

                    break;
                default:
                    throw new Exception("Non-Handled");
            }

My Json Serializable Class

Вот определение класса, используемого для JSONserialization.

    public class WillyTC 
    {
        public WillyProperties WillyCustomProperties;
        public WillyTC()
        {
            WillyCustomProperties = new WillyProperties();
        }

        public class WillyProperties
        {
            public readonly string PerimetreExterne_Fr = "Longueur à découper extérieure";
            public readonly string PerimetreExterne_En = "Cutting Length-Outer";
            public readonly string PerimetreInterne_Fr = "Longueur à découper des boucles intérieures";
            public readonly string PerimetreInterne_En = "Cutting Length-Inner";
            public readonly string NbDecoupeInterne_Fr = "Découpes";
            public readonly string NbDecoupeInterne_En = "Cut Outs";
            public readonly string AireBrut_Fr = "Surface du flanc de tôle";
            public readonly string AireBrut_En = "Bounding Box Area";
            public readonly string AirePiece_Fr = "Surface du flanc de tôle brut";
            public readonly string AirePiece_En = "Bounding Box Area-Blank";
            public readonly string Pliages_Fr = "Plis";
            public readonly string Pliages_En = "Bends";
            public readonly string Epaisseur_Fr = "Epaisseur de tôlerie";
            public readonly string Epaisseur_En = "Sheet Metal Thickness";
            public readonly string LongueurRect_Fr = "Longueur du flanc de tôle";
            public readonly string LongueurRect_En = "Bounding Box Length";
            public readonly string LargeurRect_Fr = "Largeur du flanc de tôle";
            public readonly string LargeurRect_En = "Bounding Box Width";
            public readonly string NumeroMateriel = "NumeroMateriel";
            public readonly string RPliage = "RPliage";
            public readonly string VPliage = "VPliage";
        }
}

Спасибо!

Ответы [ 3 ]

1 голос
/ 23 мая 2019

Я думаю, что локализация решит это. Кажется, вы хотите загрузить строки на основе языка, и для этого уже есть механизм. Очень грубый пример:

public class WillyTC
{
    public string PerimetreExterne { get; }
    public string PerimetreInterne { get; }
    public string NbDecoupeInterne { get; }
    public string AireBrut { get; }
    public string AirePiece { get; }
    public string Pliages { get; }
    public string Epaisseur { get; }
    public string LongueurRect { get; }
    public string LargeurRect { get; }
    public string NumeroMateriel { get; }
    public string RPliage { get; }
    public string VPliage { get; }

    public WillyTC() : this("fr") { }

    public WillyTC(string cultureName)
    {

        var culture = CultureInfo.CreateSpecificCulture(cultureName);
        Thread.CurrentThread.CurrentCulture = culture;
        Thread.CurrentThread.CurrentUICulture = culture;

        PerimetreExterne = Resources.strings.PerimetreExterne;
        PerimetreInterne = Resources.strings.PerimetreInterne;
        NbDecoupeInterne = Resources.strings.NbDecoupeInterne;
        AireBrut = Resources.strings.AireBrut;
        AirePiece = Resources.strings.AirePiece;
        Pliages = Resources.strings.Pliages;
        Epaisseur = Resources.strings.Epaisseur;
        LongueurRect = Resources.strings.LongueurRect;
        LargeurRect = Resources.strings.LargeurRect;
        NumeroMateriel = Resources.strings.NumeroMateriel;
        RPliage = Resources.strings.RPliage;
        VPliage = Resources.strings.VPliage;
    }
}

Вы можете создать экземпляр класса с соответствующей культурой:

class Program
{
    static void Main(string[] args)
    {
        var inFrench = new WillyTC();
        var inEnglish = new WillyTC("en-US");
    }
}

И вы установили файлы ресурсов с локализованным текстом:

enter image description here

enter image description here

0 голосов
/ 24 мая 2019

Должен ли я просто сделать это?

Вилли Класс

public class WillyTC : Willy
{
    public Dictionary<string, Dictionary<string, string>> WillyCustomProperties = new Dictionary<string, Dictionary<string, string>>();


    public WillyTC() : base()
    {
        WillyCustomProperties.Add("PerimetreExterne", new Dictionary<string, string> { { "french", "Longueur à découper extérieure" } , { "english", "Cutting Length-Outer" } });
        WillyCustomProperties.Add("PerimetreInterne", new Dictionary<string, string> { { "french", "Longueur à découper des boucles intérieures" } , { "english", "Cutting Length-Inner" } });
        WillyCustomProperties.Add("NbDecoupeInterne", new Dictionary<string, string> { { "french", "Découpes" } , { "english", "Cut Outs" } });
        WillyCustomProperties.Add("AireBrut", new Dictionary<string, string> { { "french", "Surface du flanc de tôle" } , { "english", "Bounding Box Area" } });
        WillyCustomProperties.Add("AirePiece", new Dictionary<string, string> { { "french", "Surface du flanc de tôle brut" } , { "english", "Bounding Box Area-Blank" } });
        WillyCustomProperties.Add("Pliages", new Dictionary<string, string> { { "french", "Plis" } , { "english", "Bends" } });
        WillyCustomProperties.Add("Epaisseur", new Dictionary<string, string> { { "french", "Epaisseur de tôlerie" } , { "english", "Sheet Metal Thickness" } });
        WillyCustomProperties.Add("LongueurRect", new Dictionary<string, string> { { "french", "Longueur du flanc de tôle" } , { "english", "Bounding Box Length" } });
        WillyCustomProperties.Add("LargeurRect", new Dictionary<string, string> { { "french", "Largeur du flanc de tôle" } , { "english", "Bounding Box Width" } });
        WillyCustomProperties.Add("NumeroMateriel", new Dictionary<string, string> { { "french", "NumeroMateriel" } , { "english", "NumeroMateriel" } });
        WillyCustomProperties.Add("RPliage", new Dictionary<string, string> { { "french", "RPliagee" } , { "english", "RPliage" } });
        WillyCustomProperties.Add("VPliage", new Dictionary<string, string> { { "french", "VPliage" } , { "english", "VPliage" } });

    }
}

Используя это

        string lang = parentType.solidworksController.swApp.GetCurrentLanguage();
        PerimetreInterne = GetCustomPropDouble(customPropertyManager, ConfigController.config.TC.willy.WillyCustomProperties[nameof(PerimetreInterne)][lang]);
        PerimetreExterne = GetCustomPropDouble(customPropertyManager, ConfigController.config.TC.willy.WillyCustomProperties[nameof(PerimetreExterne)][lang]);
        NbDecoupeInterne = GetCustomPropInt(customPropertyManager, ConfigController.config.TC.willy.WillyCustomProperties[nameof(NbDecoupeInterne)][lang]);
        AireBrut = GetCustomPropDouble(customPropertyManager, ConfigController.config.TC.willy.WillyCustomProperties[nameof(AireBrut)][lang]);
        AirePiece = GetCustomPropDouble(customPropertyManager, ConfigController.config.TC.willy.WillyCustomProperties[nameof(AirePiece)][lang]);
        Pliages = GetCustomPropInt(customPropertyManager, ConfigController.config.TC.willy.WillyCustomProperties[nameof(Pliages)][lang]);
        Epaisseur = GetCustomPropDouble(customPropertyManager, ConfigController.config.TC.willy.WillyCustomProperties[nameof(Epaisseur)][lang]);
        LongueurRect = GetCustomPropDouble(customPropertyManager, ConfigController.config.TC.willy.WillyCustomProperties[nameof(LongueurRect)][lang]);
        LargeurRect = GetCustomPropDouble(customPropertyManager, ConfigController.config.TC.willy.WillyCustomProperties[nameof(LargeurRect)][lang]);
0 голосов
/ 23 мая 2019

Вы можете сохранить имена свойств в поиске по словарю, в словаре ресурсов или в таблице SQL, а затем попытаться получить это значение и использовать его.Это также дает вам возможность легко менять языки вне вашего кода.

Dictionary<string,string> languageConfigLookup = 
    new Dictionary<string,string>() {
        {"french",JSonConfigFile.FrenchPropName},
        {"english",JSonConfigFile.EnglishPropName}
    };

if (languageConfigLookup.TryGetValue(GetCurrentLanguage().ToLower(), out string propertyName))
{
   Value2Get = GetSolidworksProp(propertyName);
}
else 
{ 
   throw new Exception("Not-Handled");
}
...