1
我不需要使用通過Activator createInstance創建新實例,那麼爲什麼我需要它呢?在哪些情況下我需要使用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();
}
}
}
@Marck:+1解釋 – 2011-04-25 11:56:50
我需要更深入的解釋:( – programmerist 2011-04-25 12:45:38
@programmerist - 你不明白什麼?Marc列舉了你必須使用Activator.CreateInstance的情況,這就是你所問的。大多數情況下,最好是直接調用構造函數,就像第二個代碼中使用'new()'約束。 – Justin 2011-04-25 13:04:50