C# Activator和new的区别

1、你需要动态的创建一个实例模型的时候,就用Activator.CreateInstance(Type type);如果是明确的知道要创建哪个实例的模型,就可以用 new Class()了

T tInstance= (T)Activator.CreateInstance(typeof(T), new object[] { message });

2、基于接口的Remoting对象是不能用new来创建的,可以直接使用Activator来创建
3、C#中Activator.CreateInstance()方法用法分析
https://www.cnblogs.com/rinack/p/5831153.html
4、.NET C# 三种实例化一个类的方式的性能比较
https://www.cnblogs.com/liuning8023/archive/2012/07/01/2572073.html


public List<T> FindAl1<T>() where T : BaseModel
        {
            Type type = typeof(T);
            string sq1 = $”SELECT { string.Join(",",type.GetProperties().Select(p => $"[{p.Name}]"))}
            FROM[{ type.Name}]";
              using(SqlConnection conn = new SqlConnection(ConnectionStringCustomers))
                {
                SqlCommand command = new Sq1Command(sq1, conn);
                conn.Open();
                var reader = command.ExecuteReader();
                List<T> tList = new List<T>();
                //object o0bject = Activator. CreateInstance (type) ;
                while (reader.Read())
                {
                    object o0bject = Activator.CreateInstance(type);
                    foreach (var prop in type.GetProperties()
                        {
                        prop.SetValue(o0bject,reader[prop.Name] is DBNull ? null : reader[prop.Name]);
                    }
                    tList.Add((T)o0bject);
                    return tList;
                }
            }
        }
posted @ 2020-02-10 21:33  乾子  阅读(278)  评论(0编辑  收藏  举报