为什么我需要使用Activator CreateInstance
本文关键字:Activator CreateInstance 为什么 | 更新日期: 2023-09-27 17:53:00
我不需要使用通过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();
}
}
}
场景:
- 你没有使用泛型,而只是基于
Type
的代码 - 你正在使用泛型,但构造函数接受参数-
new()
仅限于无参数构造函数 - 有一个无参数的构造函数,但它是不可访问的(IIRC激活器将使用私有构造函数,如果你问)
但是,是的,在您的情况下,new()
约束是理想的。