简体   繁体   English

C#使用内部具有变量名称的字符串设置变量

[英]C# Set variable using string that has variable name inside

*Switched over to serailization. *切换到Serialization。

Summary: I have all the variables pre-defined as null / 0. I want to set them using data from and XML document. 摘要:我所有的变量都预定义为null /0。我想使用XML文档中的数据进行设置。 The document contains the exact same names as the variables. 该文档包含与变量完全相同的名称。 I don't want to use a bunch of else ifs so I'm trying to do it based on the names I pull from the XML document. 我不想使用其他ifs,因此我试图根据我从XML文档中提取的名称进行操作。

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Xml;
using System.IO;

public class ShipAttributes
{
    // Model Information
    string name;
    string modelName;
    string firingPosition;
    string cameraPosition;
    string cargoPosition;
    Vector3 cameraDistance;

    // Rotation
    float yawSpeed;
    float pitchSpeed;
    float rollSpeed;

    // Speed
    float maxSpeed;
    float cruiseSpeed;
    float drag;
    float maxAcceleration;
    float maxDeceleration;

    // Physics Properties
    float mass;

    // Collection Capacity
    float cargoSpace;

    // Combat [Defense]
    float structureHealth;
    float armorHealth;
    float shieldHealth;
    float shieldRadius;

    // Combat [Assault]
    float missileRechargeTime;
    float fireRate; 

    // Currency Related
    float cost;
    float repairMultiplier;

void PopulateShipList()
{
    if (shipList != null)
        return;

    string filepath = Application.dataPath + "/Resources/shipsdata.xml";

    XmlRootAttribute xml_Root = new XmlRootAttribute();
    xml_Root.ElementName = "SHIPS";
    xml_Root.IsNullable = true;
    //using (var stream = new FileStream(filepath, FileMode.Open, FileAccess.Read)) 
    //{
        StringReader stringReader = new StringReader(filepath);
        stringReader.Read();
        XmlReader xRdr = XmlReader.Create(stringReader);
        XmlSerializer xml_s = new XmlSerializer(typeof(List<ShipAttributes>), xml_Root);
        shipList= (List<ShipAttributes>)xml_s.Deserialize(xRdr);
    //}
}
public ShipAttributes LoadShip(string inName)
{
    PopulateShipList();
    foreach (ShipAttributes att in shipList)
    {
        if (att.name == inName)
        {
            att.shipList = shipList;
            return att;
        }
    }

    return null;
}

*Note Variables in the XML files have the exact same Format and Name as the variables in the class. *注意XML文件中的变量与类中的变量具有完全相同的格式和名称。 maxSpeed in Class is maxSpeed in XML file. 类中的maxSpeed是XML文件中的maxSpeed。

My XML looks like this -- 我的XML看起来像这样-

<?xml version="1.0" encoding="UTF-8 without BOM" ?>

     <SHIPS>
        <SHIP>
            <name>Default</name>
            <id>0</id>
            <modelName>Feisar_Ship</modelName>
            <firingPosition>null</firingPosition>
            <cameraPosition>null</cameraPosition>
            <cargoPosition>null</cargoPosition>
            <cameraDistance>null</cameraDistance>
            <yawSpeed>2000.0</yawSpeed>
            <pitchSpeed>3000.0</pitchSpeed>
            <rollSpeed>10000.15</rollSpeed>
            <maxSpeed>200000.0</maxSpeed>
            <cruiseSpeed>100000.0</cruiseSpeed>
            <drag>0.0</drag>
            <maxAcceleration>null</maxAcceleration>
            <maxDeceleration>null</maxDeceleration>
            <mass>5000.0</mass>
            <cargoSpace>150.0</cargoSpace>
            <structureHealth>100.0</structureHealth>
            <armorHealth>25.0</armorHealth>
            <shieldHealth>25.0</shieldHealth>
            <shieldRadius>30.0</shieldRadius>
            <missileRechargeTime>2.0</missileRechargeTime>
            <fireRate>0.5f</fireRate>
            <cost>0</cost>
            <repairMultiplier>1.0</repairMultiplier>
        </SHIP>   
     </SHIPS

> >

Yes Yes I know... Feisar! 是的,我知道... Feisar! Just place holders for now from turbosquid. 现在就从turbosquid放置支架。

Create a class to hold the values you are reading in and use XML Serialization. 创建一个类来保存您正在阅读的值,然后使用XML序列化。

Microsoft Tutorial Microsoft教程

Tech Pro Tutorial 技术专业教程

MSDN: XmlSerializer MSDN:XmlSerializer

EDIT : 编辑:

If the XML is exactly the same as the class code you posted, the following should allow you to get a class of ShipAttributes : 如果XML与您发布的类代码完全相同,则以下内容应允许您获得ShipAttributes类:

ShipAttributes attributes = null;
string filepath = "/path/to/xml";

using (var stream = new FileStream(filepath, FileMode.Open, FileAccess.Read)) {
    var xml_s = new XmlSerializer(typeof(ShipAttributes));

    attributes = (ShipAttributes)xml_s.Deserialize(stream);
}

Edit 2 : Multiple Ships 编辑2:多艘船

In your comment, you said that the file contains multiple ShipAttribute descriptions. 在您的评论中,您说该文件包含多个ShipAttribute描述。 The way to handle that is the same as above, but deserialize the file into the type List<ShipAttribute> as follows: 处理方法与上面相同,但是将文件反序列化为List<ShipAttribute>类型,如下所示:

List<ShipAttributes> ships = null;
string filepath = "/path/to/xml";

using (var stream = new FileStream(filepath, FileMode.Open, FileAccess.Read)) {
    var xml_s = new XmlSerializer(typeof(List<ShipAttributes>));

    ships= (List<ShipAttributes>)xml_s.Deserialize(stream);
}

Once you've done that, you have all of the ships in memory and can pick the one out of the list you need using Linq etc. 完成此操作后,您便拥有了所有船只,并可以使用Linq等从列表中选择其中的一个。

ASSUMING YOU XML FILE 假设您的XML文件

<?xml version="1.0" encoding="utf-8"?>
<Variables>      
    <VariableName1>1</VariableName1>
    <VariableName2>test</VariableName2>
    <VariableName3>test2</VariableName3>    
</Variables>



var data = XDocument.Load("YourXML.xml");
var xmldata = from x in data.Descendants("Variables")                        
                        select x;

notes.Select(_BuildPropertyFromElement);



private Yourclassname _BuildNoteFromElement(XElement element)
    {
      var type = typeof(**Yourclassname**);
      var Details = new Yourclassname();

      foreach (var propInfo in type.GetProperties())
      {
         var rawValue = element.Element(propInfo.Name).Value;
         var convertedValue = propInfo.PropertyType == typeof(DateTime) ?         (object)Convert.ToDateTime(rawValue) : rawValue;
            propInfo.SetValue(Details , convertedValue, null);
                }

                return Details ;
            }

YOURCLASSNAME is the name of the class which would have all the properties you want to set to YOURCLASSNAME是类的名称,该类将具有您要设置为的所有属性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM