简体   繁体   English

C#:使用字符串变量作为名称实例化一个类

[英]C#: Instantiate a Class with String Variable as Name

I was wondering if it is possible to instantiate a class with a string variable as its name in C#. 我想知道是否可以在C#中使用字符串变量作为其实例化一个类。 I don't know how else to explain it other than this. 除此以外,我不知道还有什么其他解释。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
public class Product
{
    string name;
    decimal cost;

    Product(string _name, decimal _cost)
    {
        name = _name;
        cost = _cost;
    }
}
class Program
{
    static void Main(string[] args)
    {
        string nameForInstantiatedClass = "DellComputer";
        Product nameForInstantiatedClass = new Product("Inspiron", 399.99m);
    }
}
}

Is it possible to do something like this or to the same effect, using a string to declare the name of an instantiated class or is it just impossible to do? 是否可以使用字符串声明实例化类的名称来执行类似的操作或达到相同的效果,还是做不到? Any help is appreciated. 任何帮助表示赞赏。

One thing that comes to my mind is to use a 我想到的一件事是使用

 var products = new Dictionary<string,Product>();

and then you can save / retrieve items like this 然后您可以保存/检索这样的项目

products.Add(nameForInstantiatedClass, ProductObject);
Product dellComp = products[nameForInstantiatedClass]

I don't know why you want to do that. 我不知道你为什么要这么做。 Is there an other logic for you? 您还有其他逻辑吗? You could put the instance in a List or Dictionary like : 您可以将实例放入列表或字典中,例如:

Dictionary<String, Product> dict = new Dictionary()
dict.add("DellComputer", new Product("",399.99m);

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

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