我想知道是否可以在C#中实例化一个带有字符串变量的类作为其名称。除此之外,我不知道如何解释它。
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);
}
}
}
是否可以做类似的事情或相同的效果,使用字符串来声明实例化类的名称,或者它是不可能的?任何帮助表示赞赏。
答案 0 :(得分:1)
我想到的一件事是使用
var products = new Dictionary<string,Product>();
然后你可以保存/检索这样的项目
products.Add(nameForInstantiatedClass, ProductObject);
Product dellComp = products[nameForInstantiatedClass]
答案 1 :(得分:0)
我不知道你为什么要这样做。 你有其他逻辑吗? 您可以将实例放在List或Dictionary中,如:
Dictionary<String, Product> dict = new Dictionary()
dict.add("DellComputer", new Product("",399.99m);