AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题 / 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

我的自定义类型有许多不同的属性,其中大多数是可选的,如何使其更紧凑

  • 772

我正在开发一个用于修改游戏的工具,我想将自定义类型重新制作为 C# 类。此类型有 1 个必需属性和许多其他可选属性。我从 XML 文件中获取自定义类的所有数据,那么有什么方法可以改进这个构造函数吗?

    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;
        }
    }
}

我想到过两种可能实现的方法,即将属性作为字典或包含所有可用属性的新自定义类型传递,但我不确定它们是否会更好。

c#
  • 1 1 个回答
  • 49 Views

1 个回答

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

    那么,定义一个类来保存所有可选属性:

    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
        }
    }
    

    并将该类传递ItemData给Item构造函数:

     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;
         }
     }
    

    您还必须更新您的Item.GetAsXml()方法以正确序列化您的数据:

    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;
    }
    

    然后您可以创建如下项目:

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

    当您序列化上述项目时:

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

    您将获得以下输出:

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

相关问题

  • Polly DecorlatedJitterBackoffV2 - 如何计算完成所有重试所需的最长时间?

  • Wpf。在 ScrollViewer 中滚动 DataGrid

  • 我在使用 .NET MAUI MVVM 的游戏页面上获得的分数在其他页面上不可见。如何在本地设备中保存分数数据

  • 从 DataTemplate 内部将 TreeView 层次结构与 HierarchicalDataTemplate 结合使用

  • 如何改进 .NET 中的验证接口?

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行?

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    何时应使用 std::inplace_vector 而不是 std::vector?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Marko Smith

    我正在尝试仅使用海龟随机和数学模块来制作吃豆人游戏

    • 1 个回答
  • Martin Hope
    Aleksandr Dubinsky 为什么 InetAddress 上的 switch 模式匹配会失败,并出现“未涵盖所有可能的输入值”? 2024-12-23 06:56:21 +0800 CST
  • Martin Hope
    Phillip Borge 为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行? 2024-12-12 20:46:46 +0800 CST
  • Martin Hope
    Oodini 具有指定基础类型但没有枚举器的“枚举类”的用途是什么? 2024-12-12 06:27:11 +0800 CST
  • Martin Hope
    sleeptightAnsiC `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它? 2024-11-09 07:18:53 +0800 CST
  • Martin Hope
    The Mad Gamer 何时应使用 std::inplace_vector 而不是 std::vector? 2024-10-29 23:01:00 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST
  • Martin Hope
    MarkB 为什么 GCC 生成有条件执行 SIMD 实现的代码? 2024-02-17 06:17:14 +0800 CST

热门标签

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

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve