简体   繁体   English

字典/列表中的C#存储类类型

[英]C# Store Class Type in a Dictionary/List

Is there a way to store the class type and not an instance of a class in my dictionary/list? 有没有办法在我的字典/列表中存储类类型而不是类的实例?

I want to do something like this: 我想做这样的事情:

public class FoodNeed : BaseNeeds
{
    public Dictionary<Type, float> consumptionlist = new Dictionary<Type, float>();

    public FoodNeed()
    {
        consumptionlist.Add (Meat, 0.3f);
    }
}

Meat is is class and instead of adding a " new Meat() " to the dictionaray i just want to store the type (beacause i think it's not necessary to create the complete instace just for the type), is that possible? Meat是类,而不是在dictionaray上添加“ new Meat() ”,我只想存储类型(因为我认为不必为该类型创建完整的实例),这可能吗? Or do i have to store for example "Meat" as string and parse this later on. 还是我必须将例如“ Meat”存储为字符串并稍后解析。 Or is something like this a big no-no and this has to be done differently. 还是像这样的大禁忌,这必须以不同的方式进行。

Thank you for your help 谢谢您的帮助

I believe you are looking for typeof to get the type of meat: 我相信您正在寻找typeof来获取肉的类型:

public class FoodNeed : BaseNeeds
{
    public Dictionary<Type, float> consumptionlist = new Dictionary<Type, float>();

    public FoodNeed()
    {
        consumptionlist.Add(typeof(Meat), 0.3f);
    }
}

Please use typeof , 请使用typeof

public class FoodNeed : BaseNeeds
{
    public Dictionary<Type, float> consumptionlist = new Dictionary<Type, float>();

    public FoodNeed()
    {
        consumptionlist.Add (typeof(Meat), 0.3f);
    }
}

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

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