建立在C#中的动态变量名 [英] Creating dynamic variable names in C#

查看:1340
本文介绍了建立在C#中的动态变量名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写一个简单的角色扮演游戏在C#中更加熟悉的语言。

I am trying to write a simple role playing game in C# to become more familiar with the language.

我有一个从CSV文件加载数据的类,创建一个对象,并在字典它地方。因为游戏的每一个方面都有不同的数据(物品,角色,技能等),我已经设置了每一种为一类,但是这需要我为每一个重新实现的load()方法。这样做的5〜6倍后,我

I have a class that loads data from CSV file, creates an object, and places it in a dictionary. Because every aspect of the game has different data (items, actors, skills, etc), I have set up each of these as a class, but this requires me to re-implement a Load() method for each one. After doing this 5 or 6 times, I am wondering if there isn't a better way to implement this.

基本上想知道如果没有实现这个更好的方法,我会想要做的是解析过该CSV的第一行包含标题,并用这些作为类变量名。目前,他们正在实现为字典的关系,所以我会做SomeClassInstance.dict [ID],在这里我将理想型SomeClassInstance.id,这是完全从文件内容生成的。

Basically, what I would want to do is parse over the first line of the CSV which contains headers, and use these as class variable names. Currently, they are implemented as a dictionary relationship, so I would do SomeClassInstance.dict["id"], where I would ideally type SomeClassInstance.id, which is entirely generated from the contents of the file.

是一个东西吗?我该怎么做呢?

Is that a thing? How do I do this?

推荐答案

如果你坚持当前的设计(CSV +字典)你可以使用ExpandoObject类让你在找什么,创建一个简单的工厂类:

If you stick to your current design (CSV + dictionary) you could use the ExpandoObject class to get what you are looking for, create a simple factory class:

public static class ObjectFactory
{
    public static dynamic CreateInstance(Dictionary<string, string> objectFromFile)
    {
        dynamic instance = new ExpandoObject();

        var instanceDict = (IDictionary<string, object>)instance;

        foreach (var pair in objectFromFile)
        {
            instanceDict.Add(pair.Key, pair.Value);
        }

        return instance;
    }
}

这工厂将制造出任何字典的对象实例,你给它,即只有一个方法来创建各种不同类型的对象。使用这样的:

This factory will create an object instance of whatever dictionary you give it, i.e. just one method to create all your different kinds of objects. Use it like this:

   // Simulating load of dictionary from file
   var actorFromFile = new Dictionary<string, string>();

   actorFromFile.Add("Id", "1");
   actorFromFile.Add("Age", "37");
   actorFromFile.Add("Name", "Angelina Jolie");

   // Instantiate dynamically
   dynamic actor = ObjectFactory.CreateInstance(actorFromFile);

   // Test using properties
   Console.WriteLine("Actor.Id = " + actor.Id + 
                     " Name = " + actor.Name + 
                     " Age = " + actor.Age);
   Console.ReadLine();



希望这有助于。 (是的,她生于1975年)

Hopes this helps. (And yes she was born 1975)

这篇关于建立在C#中的动态变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆