c# - 为什么我需要使用 Activator CreateInstance?

标签 c# .net asp.net visual-studio

我不需要通过 Activator createInstance 使用创建新实例,为什么我需要它?在什么情况下我需要使用 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; }
    }
}

我可以在没有 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();

        }
    }
}

最佳答案

场景:

  • 您没有使用泛型,而只是基于类型的代码
  • 您正在使用泛型,但构造函数采用参数 - new() 仅限于无参数构造函数
  • 有一个无参数的构造函数,但它不可访问(如果你问,IIRC Activator 将使用私有(private)构造函数)

但是,是的,在您的情况下,new() 约束是理想的。

关于c# - 为什么我需要使用 Activator CreateInstance?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5778014/

相关文章:

.net - 什么会导致项目突然忘记其中一个引用?

javascript - 如何检查列表框项目是否被选中?

c# - 无法加载文件或程序集 'VSLangProj80'

asp.net - VS.NET 2010 是否支持为 Web 应用程序设置子项目?

c# - 无法在某些 PC 上运行 c#application(使用 c++ dll)

c# - C# 编译器会自动处理 IDisposable 对象吗?

C# 让程序等到浏览器完成加载网页

.net - 衡量面向对象的指标

c# - WPF:如何卡住数据网格中的列标题

c# - 从 lambda 表达式到用户定义类型的隐式转换