简体   繁体   中英

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#. 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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