AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / coding / Perguntas / 79017984
Accepted
Planeptunia
Planeptunia
Asked: 2024-09-24 17:43:29 +0800 CST2024-09-24 17:43:29 +0800 CST 2024-09-24 17:43:29 +0800 CST

Meu tipo personalizado tem muitas propriedades diferentes, a maioria delas sendo opcionais. Como posso torná-lo mais compacto?

  • 772

Estou desenvolvendo uma ferramenta para modificar um jogo e quero refazer um tipo personalizado como classe C#. Este tipo tem 1 propriedade obrigatória e muitas outras opcionais. Estou obtendo todos os dados para a classe personalizada do arquivo XML, então há alguma maneira de tornar este construtor melhor?

    public class Item(
         string identifier,
         string? nameIdentifier = null,
         string? fallbackNameIdentifier = null,
         string? descriptionIdentifier = null,
         string? name = null,
         string? aliases = null,
         string? tags = null,
         Item.Categories? category = null,
         bool? allowAsExtraCargo = null,
         float? interactDistance = null,
         float? interactPriority = null,
         bool? interactThroughWalls = null,
         bool? hideConditionBar = null,
         bool? hideConditionInTooltip = null,
         bool? requireBodyInsideTrigger = null,
         bool? requireCursorInsideTrigger = null,
         bool? requireCampaignInteract = null,
         bool? focusOnSelected = null,
         float? offsetOnSelected = null,
         float? health = null,
         bool? allowSellWhenBroken = null,
         bool? indestructible = null,
         bool? damagedByExplosions = null,
         float? explosionDamageMultiplier = null,
         bool? damagedByProjectiles = null,
         bool? damagedByMeleeWeapons = null,
         bool? damagedByRepairTools = null,
         bool? damagedByMonsters = null,
         bool? fireProof = null,
         bool? waterProof = null,
         float? impactTolerance = null,
         float? onDamagedThreshold = null,
         float? sonarSize = null,
         bool? useInHealthInterface = null,
         bool? disableItemUsageWhenSelected = null,
         string? cargoContainerIdentifier = null,
         bool? useContainedSpriteColor = null,
         bool? useContainedInventoryIconColor = null,
         float? addedRepairSpeedMultiplier = null,
         float? addedPickingSpeedMultiplier = null,
         bool? cannotRepairFail = null,
         string? equipConfirmationText = null,
         bool? allowRotatingInEditor = null,
         bool? showContentsInTooltip = null,
         bool? canFlipX = null,
         bool? canFlipY = null,
         bool? isDangerous = null,
         int? maxStackSize = null,
         bool? allowDroppingOnSwap = null,
         bool? resizeHorizontal = null,
         bool? resizeVertical = null,
         string? description = null,
         string? allowedUpgrades = null,
         bool? hideInMenus = null,
         string? subcategory = null,
         bool? linkable = null,
         string? spriteColor = null,
         float? scale = null)
    {
        public enum Categories
        {
            Decorative,
            Machine,
            Medical,
            Weapon,
            Diving,
            Equipment,
            Fuel,
            Electrical,
            Material,
            Alien,
            Wrecked,
            Misc
        }

        // All of Item attributes
        public required string identifier = identifier;
        public string? nameIdentifier = nameIdentifier;
        public string? fallbackNameIdentifier = fallbackNameIdentifier;
        public string? descriptionIdentifier = descriptionIdentifier;

        public string? name = name;
        public string? aliases = aliases;
        public string? tags = tags;
        public Categories? category = category;

        public bool? allowAsExtraCargo = allowAsExtraCargo;
        public float? interactDistance = interactDistance;
        public float? interactPriority = interactPriority;
        public bool? interactThroughWalls = interactThroughWalls;

        public bool? hideConditionBar = hideConditionBar;
        public bool? hideConditionInTooltip = hideConditionInTooltip;
        public bool? requireBodyInsideTrigger = requireBodyInsideTrigger;
        public bool? requireCursorInsideTrigger = requireCursorInsideTrigger;

        public bool? requireCampaignInteract = requireCampaignInteract;
        public bool? focusOnSelected = focusOnSelected;
        public float? offsetOnSelected = offsetOnSelected;
        public float? health = health;

        public bool? allowSellWhenBroken = allowSellWhenBroken;
        public bool? indestructible = indestructible;
        public bool? damagedByExplosions = damagedByExplosions;
        public float? explosionDamageMultiplier = explosionDamageMultiplier;

        public bool? damagedByProjectiles = damagedByProjectiles;
        public bool? damagedByMeleeWeapons = damagedByMeleeWeapons;
        public bool? damagedByRepairTools = damagedByRepairTools;
        public bool? damagedByMonsters = damagedByMonsters;

        public bool? fireProof = fireProof;
        public bool? waterProof = waterProof;
        public float? impactTolerance = impactTolerance;
        public float? onDamagedThreshold = onDamagedThreshold;

        public float? sonarSize = sonarSize;
        public bool? useInHealthInterface = useInHealthInterface;
        public bool? disableItemUsageWhenSelected = disableItemUsageWhenSelected;
        public string? cargoContainerIdentifier = cargoContainerIdentifier;

        public bool? useContainedSpriteColor = useContainedSpriteColor;
        public bool? useContainedInventoryIconColor = useContainedInventoryIconColor;
        public float? addedRepairSpeedMultiplier = addedRepairSpeedMultiplier;
        public float? addedPickingSpeedMultiplier = addedPickingSpeedMultiplier;

        public bool? cannotRepairFail = cannotRepairFail;
        public string? equipConfirmationText = equipConfirmationText;
        public bool? allowRotatingInEditor = allowRotatingInEditor;
        public bool? showContentsInTooltip = showContentsInTooltip;

        public bool? canFlipX = canFlipX;
        public bool? canFlipY = canFlipY;
        public bool? isDangerous = isDangerous;
        public int? maxStackSize = maxStackSize;

        public bool? allowDroppingOnSwap = allowDroppingOnSwap;
        public bool? resizeHorizontal = resizeHorizontal;
        public bool? resizeVertical = resizeVertical;
        public string? description = description;

        public string? allowedUpgrades = allowedUpgrades;
        public bool? hideInMenus = hideInMenus;
        public string? subcategory = subcategory;
        public bool? linkable = linkable;

        public string? spriteColor = spriteColor;
        public float? scale = scale;

        public List<XmlElement>? children = null;

        /// <summary>
        /// Gets this Item represent
        /// </summary>
        /// <returns>XmlElement represent of the Item</returns>
        public XmlElement GetAsXml()
        {
            XmlDocument xmlDoc = new();
            XmlElement newItem = xmlDoc.CreateElement("Item");

            foreach(var attr in this.GetType().GetProperties())
            {
                if (attr.GetValue(this, null) != null)
                {
                    newItem.SetAttribute(attr.Name.ToLower(), value: attr.GetValue(this, null).ToString());
                }
            }

            newItem.InnerText = "";

            if (this.children != null)
            {
                foreach (var child in this.children)
                {
                    newItem.AppendChild(child);
                }
            }

            return newItem;
        }
    }
}

Pensei em duas maneiras de fazer isso: passando propriedades como um dicionário ou um novo tipo personalizado contendo todas as propriedades disponíveis, mas não tenho certeza se seriam melhores.

c#
  • 1 1 respostas
  • 49 Views

1 respostas

  • Voted
  1. Best Answer
    BigBoss
    2024-09-24T19:16:35+08:002024-09-24T19:16:35+08:00

    Que tal isso, defina uma classe para armazenar todas as suas propriedades opcionais:

    public class ItemData
    {
         public string? nameIdentifier { get; set; } = null;
         public string? fallbackNameIdentifier { get; set; } = null;
         public string? descriptionIdentifier { get; set; } = null;
         public string? name { get; set; } = null;
         public string? aliases { get; set; } = null;
         public string? tags { get; set; } = null;
         public ItemData.Categories? category { get; set; } = null;
         public bool? allowAsExtraCargo { get; set; } = null;
         public float? interactDistance { get; set; } = null;
         public float? interactPriority { get; set; } = null;
         public bool? interactThroughWalls { get; set; } = null;
         public bool? hideConditionBar { get; set; } = null;
         public bool? hideConditionInTooltip { get; set; } = null;
         public bool? requireBodyInsideTrigger { get; set; } = null;
         public bool? requireCursorInsideTrigger { get; set; } = null;
         public bool? requireCampaignInteract { get; set; } = null;
         public bool? focusOnSelected { get; set; } = null;
         public float? offsetOnSelected { get; set; } = null;
         public float? health { get; set; } = null;
         public bool? allowSellWhenBroken { get; set; } = null;
         public bool? indestructible { get; set; } = null;
         public bool? damagedByExplosions { get; set; } = null;
         public float? explosionDamageMultiplier { get; set; } = null;
         public bool? damagedByProjectiles { get; set; } = null;
         public bool? damagedByMeleeWeapons { get; set; } = null;
         public bool? damagedByRepairTools { get; set; } = null;
         public bool? damagedByMonsters { get; set; } = null;
         public bool? fireProof { get; set; } = null;
         public bool? waterProof { get; set; } = null;
         public float? impactTolerance { get; set; } = null;
         public float? onDamagedThreshold { get; set; } = null;
         public float? sonarSize { get; set; } = null;
         public bool? useInHealthInterface { get; set; } = null;
         public bool? disableItemUsageWhenSelected { get; set; } = null;
         public string? cargoContainerIdentifier { get; set; } = null;
         public bool? useContainedSpriteColor { get; set; } = null;
         public bool? useContainedInventoryIconColor { get; set; } = null;
         public float? addedRepairSpeedMultiplier { get; set; } = null;
         public float? addedPickingSpeedMultiplier { get; set; } = null;
         public bool? cannotRepairFail { get; set; } = null;
         public string? equipConfirmationText { get; set; } = null;
         public bool? allowRotatingInEditor { get; set; } = null;
         public bool? showContentsInTooltip { get; set; } = null;
         public bool? canFlipX { get; set; } = null;
         public bool? canFlipY { get; set; } = null;
         public bool? isDangerous { get; set; } = null;
         public int? maxStackSize { get; set; } = null;
         public bool? allowDroppingOnSwap { get; set; } = null;
         public bool? resizeHorizontal { get; set; } = null;
         public bool? resizeVertical { get; set; } = null;
         public string? description { get; set; } = null;
         public string? allowedUpgrades { get; set; } = null;
         public bool? hideInMenus { get; set; } = null;
         public string? subcategory { get; set; } = null;
         public bool? linkable { get; set; } = null;
         public string? spriteColor { get; set; } = null;
         public float? scale { get; set; } = null;
    
        public enum Categories
        {
            Decorative,
            Machine,
            Medical,
            Weapon,
            Diving,
            Equipment,
            Fuel,
            Electrical,
            Material,
            Alien,
            Wrecked,
            Misc
        }
    }
    

    E passe a ItemDataclasse para o Itemconstrutor:

     public class Item
     {
         public string Identifier { get; private set; }
         public ItemData OptionalData { get; private set; }
         public List<XmlElement>? Children { get; private set; } = null;
         public Item(string identifier, ItemData optionalData)
         {
             Identifier = identifier;
             OptionalData = optionalData;
    
             // Get the name
             string? name = OptionalData.name;
         }
     }
    

    Você também terá que atualizar seu Item.GetAsXml()método para serializar corretamente seus dados:

    public XmlElement GetAsXml()
    {
        XmlDocument xmlDoc = new();
        XmlElement newItem = xmlDoc.CreateElement("Item");
    
        // Identifier
        PropertyInfo identInfo = this.GetType().GetProperty(nameof(Identifier));
        newItem.SetAttribute(identInfo.Name.ToLower(), value: identInfo.GetValue(this, null).ToString());
    
        // Optional data attributes
        foreach (var attr in OptionalData.GetType().GetProperties())
        {
            if (attr.GetValue(OptionalData, null) != null)
            {
                newItem.SetAttribute(attr.Name.ToLower(), value: attr.GetValue(OptionalData, null).ToString());
            }
        }
    
        newItem.InnerText = "";
    
        if (this.Children != null)
        {
            foreach (var child in this.Children)
            {
                newItem.AppendChild(child);
            }
        }
    
        return newItem;
    }
    

    Você pode então criar itens como:

     ItemData itemData = new ItemData();
     itemData.name = "name1";
     itemData.health = 99;
     Item item = new Item("identifier1", itemData);
    

    Ao seriar o item acima:

     XmlElement xml = item.GetAsXml();
     Debug.WriteLine(xml.OuterXml);
    

    Você obtém esta saída:

    <Item identifier="identifier1" name="name1" health="99"></Item>
    
    • 1

relate perguntas

  • Polly DecorrelatedJitterBackoffV2 - como calcular o tempo máximo necessário para concluir todas as novas tentativas?

  • Wpf. Role o DataGrid dentro do ScrollViewer

  • A pontuação que ganhei na página do jogo com .NET MAUI MVVM não é visível em outras páginas. Como posso manter os dados de pontuação no dispositivo local

  • Use a hierarquia TreeView com HierarchicalDataTemplate de dentro de um DataTemplate

  • Como posso melhorar essa interface de validação no .NET?

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Vue 3: Erro na criação "Identificador esperado, mas encontrado 'import'" [duplicado]

    • 1 respostas
  • Marko Smith

    Por que esse código Java simples e pequeno roda 30x mais rápido em todas as JVMs Graal, mas não em nenhuma JVM Oracle?

    • 1 respostas
  • Marko Smith

    Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores?

    • 1 respostas
  • Marko Smith

    Como faço para corrigir um erro MODULE_NOT_FOUND para um módulo que não importei manualmente?

    • 6 respostas
  • Marko Smith

    `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso?

    • 3 respostas
  • Marko Smith

    Quando devo usar um std::inplace_vector em vez de um std::vector?

    • 3 respostas
  • Marko Smith

    Um programa vazio que não faz nada em C++ precisa de um heap de 204 KB, mas não em C

    • 1 respostas
  • Marko Smith

    PowerBI atualmente quebrado com BigQuery: problema de driver Simba com atualização do Windows

    • 2 respostas
  • Marko Smith

    AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos

    • 1 respostas
  • Marko Smith

    Estou tentando fazer o jogo pacman usando apenas o módulo Turtle Random e Math

    • 1 respostas
  • Martin Hope
    Aleksandr Dubinsky Por que a correspondência de padrões com o switch no InetAddress falha com 'não cobre todos os valores de entrada possíveis'? 2024-12-23 06:56:21 +0800 CST
  • Martin Hope
    Phillip Borge Por que esse código Java simples e pequeno roda 30x mais rápido em todas as JVMs Graal, mas não em nenhuma JVM Oracle? 2024-12-12 20:46:46 +0800 CST
  • Martin Hope
    Oodini Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores? 2024-12-12 06:27:11 +0800 CST
  • Martin Hope
    sleeptightAnsiC `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso? 2024-11-09 07:18:53 +0800 CST
  • Martin Hope
    The Mad Gamer Quando devo usar um std::inplace_vector em vez de um std::vector? 2024-10-29 23:01:00 +0800 CST
  • Martin Hope
    Chad Feller O ponto e vírgula agora é opcional em condicionais bash com [[ .. ]] na versão 5.2? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench Por que um traço duplo (--) faz com que esta cláusula MariaDB seja avaliada como verdadeira? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng Por que `dict(id=1, **{'id': 2})` às vezes gera `KeyError: 'id'` em vez de um TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos 2024-03-20 03:12:31 +0800 CST
  • Martin Hope
    MarkB Por que o GCC gera código que executa condicionalmente uma implementação SIMD? 2024-02-17 06:17:14 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve