为什么我需要使用激活的CreateInstance? [英] Why do I need to use Activator CreateInstance?

查看:135
本文介绍了为什么我需要使用激活的CreateInstance?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我并不需要使用通过激活createInstance建立创建新实例,所以为什么我需要它?在哪些情况下,我需要使用Activator.CreateInstance()?

 使用系统;
使用System.Collections.Generic;
使用System.Linq的;
使用System.Text;
使用的System.Reflection;

命名空间App.CreateInstance
{
    类节目
    {
        静态无效的主要(字串[] args)
        {

            新MyCustomerManager()保存并LT; MyCustomer>(新对象[] {
                     1,
                    XXX,
                    YYYY});
            }
    }

    公共类MyCustomerManager
    {
        公共无效的保存和LT; TModel的>(对象[]丘壑)
        {
            键入calcType = typeof运算(TModel的);
            对象实例= Activator.CreateInstance(calcType);
            的PropertyInfo [] ColumnNames = instance.GetType()
                                                 .GetProperties();

            的for(int i = 0; I< ColumnNames.Length;我++)
            {
                calcType.GetProperty(ColumnNames [I] .name和
                                       BindingFlags.Instance
                                     | BindingFlags.Public)
                .SetValue(例如,丘壑[I],NULL);
            }

            字符串结果=;
            的for(int i = 0; I< ColumnNames.Length;我++)
            {
                结果+ =的String.Format({0}:{1},
                    ColumnNames [I] .name和Ç
                    alcType.GetProperty(ColumnNames [I] .name和
                                          BindingFlags.Instance
                                        | BindingFlags.Public)
                           .GetValue(例如,空)的ToString());
            }
            Console.WriteLine(结果);
            Console.ReadKey();
        }
    }

    // 模型
    公共类MyCustomer
    {
        公众诠释ID {获得;组; }
        公共字符串名称{;组; }
        公共字符串姓{获得;组; }
    }
}
 

我可以做,没有Activator.CreateInstance:

 使用的System.Reflection;

命名空间App.ReflectionToGeneric4
{
    类节目
    {
        静态无效的主要(字串[] args)
        {
            [对象]瓦尔斯=新的对象[] {1,XXX,YYYY};
            新MyCustomerManager()保存并LT; MyCustomer>(瓦尔斯);
        }
    }

    // 模型
    公共类MyCustomer
    {
        公众诠释ID {获得;组; }
        公共字符串名称{;组; }
        公共字符串姓{获得;组; }
    }

    公共类MyCustomerManager
    {
        公共无效的保存和LT; TModel的>(对象[]丘壑)
                                那里的TModel:类,新的()
        {
            VAR实例=新的TModel();
            键入calcType = instance.GetType();
            的PropertyInfo [] ColumnNames = calcType.GetProperties();

            的for(int i = 0; I< ColumnNames.Length;我++)
            {
                  calcType.GetProperty(ColumnNames [I] .name和
                                          BindingFlags.Instance
                                        | BindingFlags.Public)
                          .SetValue(例如,丘壑[I],NULL);
            }
            字符串结果=;
            的for(int i = 0; I< ColumnNames.Length;我++)
            {
                结果+ =的String.Format({0}:{1},
                    ColumnNames [I] .name和
                    calcType.GetProperty(ColumnNames [I] .name和
                                          BindingFlags.Instance
                                        | BindingFlags.Public)
                            .GetValue(例如,空)的ToString());
            }
            Console.WriteLine(结果);
            Console.ReadKey();

        }
    }
}
 

解决方案

方案:

  • 您没有使用仿制药,而只是键入基于code
  • 您使用的是通用的,但在构造函数的参数 - 新()被限制为参数构造函数
  • 有参数的​​构造函数,但它是不可访问(IIRC激活将使用私有的构造函数,如果你问)

但是,是的,你的情况新()的约束是理想的。

I don't need to use create new instance via Activator createInstance so why do I need it? In which situations would I need to use Activator.CreateInstance()?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace App.CreateInstance
{
    class Program
    {
        static void Main(string[] args)
        {

            new MyCustomerManager().Save <MyCustomer>(new object[] {
                     1, 
                    "xxx", 
                    "yyyy" });
            }
    }

    public class MyCustomerManager
    {
        public void Save<TModel>(object[] Vals)
        {
            Type calcType = typeof(TModel);
            object instance = Activator.CreateInstance(calcType);
            PropertyInfo[] ColumnNames = instance.GetType()
                                                 .GetProperties();

            for (int i = 0; i < ColumnNames.Length; i++)
            {
                calcType.GetProperty(ColumnNames[i].Name,
                                       BindingFlags.Instance 
                                     | BindingFlags.Public    )
                .SetValue(instance, Vals[i], null);
            }

            string result = "";
            for (int i = 0; i < ColumnNames.Length; i++)
            {
                result += String.Format("{0}:{1}", 
                    ColumnNames[i].Name, c
                    alcType.GetProperty(ColumnNames[i].Name,
                                          BindingFlags.Instance 
                                        | BindingFlags.Public   )
                           .GetValue(instance, null).ToString());
            }
            Console.WriteLine(result);
            Console.ReadKey();
        }
    }

    // Model
    public class MyCustomer
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string SurName { get; set; }
    }
}

I can do that without Activator.CreateInstance:

using System.Reflection;

namespace App.ReflectionToGeneric4
{
    class Program
    {
        static void Main(string[] args)
        {
            object[] Vals = new object[] { 1, "xxx","yyyy" };
            new MyCustomerManager().Save<MyCustomer>(Vals);
        }
    }

    // Model
    public class MyCustomer
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string SurName { get; set; }
    }

    public class MyCustomerManager
    {
        public void Save<TModel>(object[] Vals) 
                                where TModel : class, new()
        {
            var instance = new TModel();
            Type calcType = instance.GetType();
            PropertyInfo[] ColumnNames = calcType.GetProperties();

            for (int i = 0; i < ColumnNames.Length; i++)
            {
                  calcType.GetProperty(ColumnNames[i].Name,
                                          BindingFlags.Instance
                                        | BindingFlags.Public    )
                          .SetValue(instance, Vals[i], null);
            }
            string result = "";
            for (int i = 0; i < ColumnNames.Length; i++)
            {
                result += String.Format("{0}:{1}", 
                    ColumnNames[i].Name, 
                    calcType.GetProperty(ColumnNames[i].Name, 
                                          BindingFlags.Instance 
                                        | BindingFlags.Public)
                            .GetValue(instance, null).ToString());
            }
            Console.WriteLine(result);
            Console.ReadKey();

        }
    }
}

解决方案

Scenarios:

  • you aren't using generics, but just Type-based code
  • you are using generic, but the constructor takes parameters - new() is limited to parameterless constructors
  • there is a parameterless constructor, but it is not accessible (IIRC Activator will use private constructors if you ask)

But yes, in your case the new() constraint is ideal.

这篇关于为什么我需要使用激活的CreateInstance?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆