按类型

时间:2016-09-01 17:08:47

标签: c# abstract-class

我正在尝试编写一个接受任何类型并创建其实例的泛型方法,以便我以后可以使用它:

我想动态生成的类的示例:

public class bb_ColorScaleCriteriaTypes
    {
        public Dictionary<string, int> Types { get; set; }
        public bb_ColorScaleCriteriaTypes()
        {
            this.Types = new Dictionary<string, int>()
            {
                {"LowestValue", 1},
                {"Number", 0},
                {"Percent", 3},
                {"Formula", 4},
                {"Percentile", 5},
                {"HighestValue", 2},
                {"AutomaticMax", 7},
                {"AutomaticMin", 6},
                {"None", -1}
            };
        }

        public static int byName(string name)
        {
            if (name == null)
            {
                throw new ArgumentException("name");
            }
            int intValue = new bb_ColorScaleCriteriaTypes().Types[name];
            return intValue;
        }
    }

通常我有另一个课程,我可以这样称呼:

public class bb_ColorScaleCriteriaTypesUI : DSDropDownBase
    {
        private const string NO_FAMILY_TYPES = "No types were found.";
        public bb_ColorScaleCriteriaTypesUI() : base("Color Scale Criteria Type") { }

        // Get Data Class that holds dictionary
        public static bb_ColorScaleCriteriaTypes cscTypes = new bb_ColorScaleCriteriaTypes();

        protected override SelectionState PopulateItemsCore(string currentSelection)
        {
            Items.Clear();

            Dictionary<string, int> d = new Dictionary<string, int>(cscTypes.Types);
        }

正如您所看到的,我正在实例化一个bb_ColorScaleCriteriaTypes类,然后在其上调用Types。但是,我想写一个更通用的实现,我可以做类似的事情:

    public abstract class bb_ColorScaleCriteriaTypesUI : DSDropDownBase
    {
        public bb_ColorScaleCriteriaTypesUI (string name, Type elementType) : base(name) { this.ElementType = elementType; PopulateItems(); }

        private const string noTypes = "No Types available.";
        public Type ElementType;

        // how to instantiate an instance of ElementType here? 

        protected override SelectionState PopulateItemsCore(string currentSelection)
        {
            if (this.ElementType != null)
            {
            Dictionary<string, int> d = new Dictionary<string, int>(myTypeInstance.Types); //so I can call it here
        }

在评论中看起来有点失控。

无论如何,我不介意使用Activator.CreateInstance()但是如何创建一个类型的实例并将其强制转换为类型,以便它不是通用对象?

1 个答案:

答案 0 :(得分:3)

Activator.CreateInstance()正如其他人所说的那样。返回类型不是通用对象,它是您请求的实际类型,它只是作为对象返回,因为它是所有内容的基类。

如果你想“正确的方式”,你将定义一个所有类派生/实现的接口或基类,并具有在接口/基类中一般定义的通用方法。然后,您可以使用Activator.CreateInstance()或工厂模式来新建对象,并将它们作为接口/基类返回。

相关问题